Example usage for org.apache.http.entity.mime MultipartEntityBuilder create

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntityBuilder create.

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public int post(String url, Map<String, Object> data, PostType dataType, String charset, String referrer) {
    clearPreviousRequest();//from w ww  . j  av  a  2s  . c o m

    HttpPost request = new HttpPost(url);
    HttpEntity entity = null;

    if (charset == null) {
        charset = "utf-8";
    }

    Charset detectedCharset = null;
    try {
        detectedCharset = Charset.forName(charset);
    } catch (Exception ex) {
        LOG.warn("invalid charset name {}, switching to utf-8");
        detectedCharset = Charset.forName("utf-8");
    }

    data = handleUnsupportedEncoding(data, detectedCharset);

    switch (dataType) {
    case URL_ENCODED:
        List<NameValuePair> formparams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String) {
                formparams.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
            } else {
                LOG.warn("trying to url encode non string data");
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        try {
            entity = new UrlEncodedFormEntity(formparams, detectedCharset);
        } catch (Exception ex) {
            statusCode = -1;
            exception = ex;
            return statusCode;
        }
        break;

    case MULTIPART:
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(detectedCharset)
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        ContentType formDataCT = ContentType.create("form-data", detectedCharset);
        //                formDataCT = ContentType.DEFAULT_TEXT;

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue() instanceof String) {
                builder = builder.addTextBody(key, (String) entry.getValue(), formDataCT);
            } else if (entry.getValue() instanceof byte[]) {
                builder = builder.addBinaryBody(key, (byte[]) entry.getValue());
            } else if (entry.getValue() instanceof ContentBody) {
                builder = builder.addPart(key, (ContentBody) entry.getValue());
            } else {
                exception = new UnsupportedOperationException(
                        "unssuported body type " + entry.getValue().getClass());
                return statusCode = -1;
            }
        }

        entity = builder.build();
        break;

    default:
        exception = new UnsupportedOperationException("unspported PostType " + dataType);
        return statusCode = -1;
    }

    request.setEntity(entity);
    if (referrer != null) {
        request.addHeader("Referer", referrer);
    }
    return request(request);
}

From source file:org.exmaralda.webservices.G2PConnector.java

public String callG2P(File bpfInFile, HashMap<String, Object> otherParameters)
        throws IOException, JDOMException {

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (otherParameters != null) {
        builder.addTextBody("lng", (String) otherParameters.get("lng"));
    }/*from   w ww . j  a v a 2  s  . c om*/

    // add the text file
    builder.addTextBody("iform", "bpf");
    builder.addBinaryBody("i", bpfInFile);

    // construct a POST request with the multipart entity
    HttpPost httpPost = new HttpPost(g2pURL);
    httpPost.setEntity(builder.build());
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity result = response.getEntity();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode == 200 && result != null) {
        String resultAsString = EntityUtils.toString(result);
        BASWebServiceResult basResult = new BASWebServiceResult(resultAsString);
        if (!(basResult.isSuccess())) {
            String errorText = "Call to G2P was not successful: " + resultAsString;
            throw new IOException(errorText);
        }
        String bpfOutString = basResult.getDownloadText();

        EntityUtils.consume(result);
        httpClient.close();

        return bpfOutString;
    } else {
        // something went wrong, throw an exception
        String reason = statusLine.getReasonPhrase();
        throw new IOException(reason);
    }
}

From source file:io.swagger.client.api.DefaultApi.java

/**
 * One-shot channel scene//from w w w  .  j av  a  2 s. c  o  m
 * Retrieves the list of cards related to the content currently being broadcasted in the provided channel
 * @param authorization Authorization token (&#39;Bearer &lt;token&gt;&#39;)
 * @param channelId Client channel ID
 * @param acceptLanguage Client locale, as &lt;language&gt;-&lt;country&gt;
 * @param contentType application/json
 * @param relations Indicates if the received scene cards should contain the scene hierarchy (true) or be a flat list of the main scene items (false)
 * @param imageSize Size of the images returned in the response
 * @return List<Card>
 */
public List<Card> getStaticChannelScene(String authorization, String channelId, String acceptLanguage,
        String contentType, Boolean relations, String imageSize) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'authorization' is set
    if (authorization == null) {
        throw new ApiException(400,
                "Missing the required parameter 'authorization' when calling getStaticChannelScene");
    }

    // verify the required parameter 'channelId' is set
    if (channelId == null) {
        throw new ApiException(400,
                "Missing the required parameter 'channelId' when calling getStaticChannelScene");
    }

    // create path and map variables
    String localVarPath = "/channels/{channel_id}/static".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "channel_id" + "\\}", apiInvoker.escapeString(channelId.toString()));

    // query params
    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> localVarHeaderParams = new HashMap<String, String>();
    // form params
    Map<String, String> localVarFormParams = new HashMap<String, String>();

    localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "relations", relations));
    localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "image_size", imageSize));

    localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization));
    localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage));
    localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType));

    String[] localVarContentTypes = { "application/json" };
    String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json";

    if (localVarContentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        localVarPostBody = localVarBuilder.build();
    } else {
        // normal form params
    }

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams,
                localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType);
        if (localVarResponse != null) {
            return (List<Card>) ApiInvoker.deserialize(localVarResponse, "array", Card.class);
        } else {
            return null;
        }
    } catch (ApiException ex) {
        throw ex;
    }
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Creates an <tt>HttpMethod</tt> instance according to the specified parameters.
 * @param webRequest the request/*w w  w.j  a v a  2s .  c  om*/
 * @param httpClientBuilder the httpClientBuilder that will be configured
 * @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters
 * @throws IOException
 * @throws URISyntaxException
 */
@SuppressWarnings("deprecation")
private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder)
        throws IOException, URISyntaxException {

    final String charset = webRequest.getCharset();

    // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request
    // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're
    // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode
    // chars in the URL.
    final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset);

    // URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path
    // what shouldn't happen here
    URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(),
            escapeQuery(url.getQuery()), null);
    if (getVirtualHost() != null) {
        uri = URI.create(getVirtualHost());
    }
    final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri);
    setProxy(httpMethod, webRequest);
    if (!(httpMethod instanceof HttpEntityEnclosingRequest)) {
        // this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD
        if (!webRequest.getRequestParameters().isEmpty()) {
            final List<NameValuePair> pairs = webRequest.getRequestParameters();
            final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
            final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
            uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query,
                    null);
            httpMethod.setURI(uri);
        }
    } else { // POST as well as PUT and PATCH
        final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod;

        if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) {
            final HttpPost postMethod = (HttpPost) method;
            if (webRequest.getRequestBody() == null) {
                final List<NameValuePair> pairs = webRequest.getRequestParameters();
                final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
                final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
                final StringEntity urlEncodedEntity = new StringEntity(query, charset);
                urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
                postMethod.setEntity(urlEncodedEntity);
            } else {
                final String body = StringUtils.defaultString(webRequest.getRequestBody());
                final StringEntity urlEncodedEntity = new StringEntity(body, charset);
                urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
                postMethod.setEntity(urlEncodedEntity);
            }
        } else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) {
            final Charset c = getCharset(charset, webRequest.getRequestParameters());
            final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode();
            builder.setCharset(c);

            for (final NameValuePair pair : webRequest.getRequestParameters()) {
                if (pair instanceof KeyDataPair) {
                    buildFilePart((KeyDataPair) pair, builder);
                } else {
                    builder.addTextBody(pair.getName(), pair.getValue(),
                            ContentType.create("text/plain", charset));
                }
            }
            method.setEntity(builder.build());
        } else { // for instance a PUT or PATCH request
            final String body = webRequest.getRequestBody();
            if (body != null) {
                method.setEntity(new StringEntity(body, charset));
            }
        }
    }

    configureHttpProcessorBuilder(httpClientBuilder, webRequest);

    // Tell the client where to get its credentials from
    // (it may have changed on the webClient since last call to getHttpClientFor(...))
    final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider();

    // if the used url contains credentials, we have to add this
    final Credentials requestUrlCredentials = webRequest.getUrlCredentials();
    if (null != requestUrlCredentials && webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) {
        final URL requestUrl = webRequest.getUrl();
        final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
        // updating our client to keep the credentials for the next request
        credentialsProvider.setCredentials(authScope, requestUrlCredentials);
        httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
    }

    // if someone has set credentials to this request, we have to add this
    final Credentials requestCredentials = webRequest.getCredentials();
    if (null != requestCredentials) {
        final URL requestUrl = webRequest.getUrl();
        final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
        // updating our client to keep the credentials for the next request
        credentialsProvider.setCredentials(authScope, requestCredentials);
        httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
    }
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER);

    return httpMethod;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java

/**
 * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug.
 *
 * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293,
 * which is related to http://sourceforge.net/p/htmlunit/bugs/535/
 *
 * @throws Exception if the test fails/*from   w  ww  .  jav a  2 s .  c o m*/
 */
@Test
public void uploadFileWithNonASCIIName_HttpClient() throws Exception {
    final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt";
    final String path = getClass().getClassLoader().getResource(filename).toExternalForm();
    final File file = new File(new URI(path));
    assertTrue(file.exists());

    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/upload2", Upload2Servlet.class);

    startWebServer("./", null, servlets);
    final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8"));
    builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));

    filePost.setEntity(builder.build());

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    final HttpResponse httpResponse = clientBuilder.build().execute(filePost);

    InputStream content = null;
    try {
        content = httpResponse.getEntity().getContent();
        final String response = new String(IOUtils.toByteArray(content));
        //this is the value with ASCII encoding
        assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response));
    } finally {
        IOUtils.closeQuietly(content);
    }
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private String performHttpBulkRequestToBKU(String xmlRequest, BulkRequestPackage pack, SignParameter parameter)
        throws ClientProtocolException, IOException, IllegalStateException {
    CloseableHttpClient client = null;/* www  .j av a 2  s  . c  om*/
    try {
        client = buildHttpClient();
        HttpPost post = new HttpPost(this.bkuUrl);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setCharset(Charset.forName("UTF-8"));
        entityBuilder.addTextBody(XMLREQUEST, xmlRequest,
                ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8")));

        if (parameter != null) {
            String transactionId = parameter.getTransactionId();
            if (transactionId != null) {
                entityBuilder.addTextBody("TransactionId_", transactionId);
            }
        }

        for (SignRequestPackage signRequestPackage : pack.getSignRequestPackages()) {

            if (pack != null && signRequestPackage != null
                    && signRequestPackage.getCmsRequest().getSignatureData() != null) {
                entityBuilder.addBinaryBody("fileupload",
                        PDFUtils.blackOutSignature(signRequestPackage.getCmsRequest().getSignatureData(),
                                signRequestPackage.getCmsRequest().getByteRange()));
            }

        }

        post.setEntity(entityBuilder.build());

        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());

        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;
            Header[] headers = response.getAllHeaders();

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue());
                    logger.debug("Response Header : {}", hdr.toString());
                    holder.getProcessInfo().add(hdr);
                }
            }

            BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE);
            logger.debug("Response Header : {}", hdr.toString());
            holder.getProcessInfo().add(hdr);
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        response = null;
        rd = null;

        logger.trace(result.toString());
        return result.toString();
    } catch (PDFIOException e) {
        throw new PdfAsWrappedIOException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:io.swagger.client.api.CameraApi.java

/**
* Start recording a movie//from  ww  w  . j a  va  2 s.  c  om
* 
        
*/
public void captureStartPost(final Response.Listener<String> responseListener,
        final Response.ErrorListener errorListener) {
    Object postBody = null;

    // create path and map variables
    String path = "/capture/start".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams,
                contentType, authNames, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String localVarResponse) {
                        responseListener.onResponse(localVarResponse);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        errorListener.onErrorResponse(error);
                    }
                });
    } catch (ApiException ex) {
        errorListener.onErrorResponse(new VolleyError(ex));
    }
}

From source file:com.smartling.api.sdk.FileApiClientAdapterImpl.java

private HttpPost createFileUploadHttpPostRequest(final String apiParameters, final ContentBody contentBody) {
    final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
            .addPart(FileApiParams.FILE, contentBody);

    final HttpPost httpPost = new HttpPost(String.format(UPLOAD_FILE_API_URL, baseApiUrl) + apiParameters);
    httpPost.setEntity(multipartEntityBuilder.build());

    return httpPost;
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a resource using Smartsheet REST API.
 *
 * Exceptions:/*  ww w.  j a va  2  s. com*/
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type
 * @param path the relative path of the resource collections
 * @param objectClass the resource object class
 * @param object the object to create
 * @return the created resource
 * @throws SmartsheetException the smartsheet exception
 */
protected <T> T createResourceWithAttachment(String path, Class<T> objectClass, T object, String partName,
        InputStream inputStream, String contentType, String attachmentName) throws SmartsheetException {
    Util.throwIfNull(path, object);
    Util.throwIfEmpty(path);

    HttpRequest request;
    final String boundary = "----" + System.currentTimeMillis();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(path));

    try {
        uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(object),
            ContentType.APPLICATION_JSON);
    builder.addBinaryBody("file", inputStream, ContentType.create(contentType), attachmentName);
    org.apache.http.HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    T obj = null;
    //implement switch case
    try {
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        obj = this.getSmartsheet().getJsonSerializer()
                .deserializeResult(objectClass, responseEntity.getContent()).getResult();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return obj;
}