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

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

Introduction

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

Prototype

public MultipartEntityBuilder setMode(final HttpMultipartMode mode) 

Source Link

Usage

From source file:io.confluent.support.metrics.utils.WebClient.java

/**
 * Sends a POST request to a web server//from  w  ww  . j a va 2 s .com
 * @param customerId: customer Id on behalf of which the request is sent
 * @param bytes: request payload
 * @param httpPost: A POST request structure
 * @return an HTTP Status code
 */
public static int send(String customerId, byte[] bytes, HttpPost httpPost) {
    int statusCode = DEFAULT_STATUS_CODE;
    if (bytes != null && bytes.length > 0 && httpPost != null && customerId != null) {

        // add the body to the request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("cid", customerId);
        builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, "filename");
        httpPost.setEntity(builder.build());

        // set the HTTP config
        final RequestConfig config = RequestConfig.custom().setConnectTimeout(requestTimeoutMs)
                .setConnectionRequestTimeout(requestTimeoutMs).setSocketTimeout(requestTimeoutMs).build();

        // send request
        try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
                .build(); CloseableHttpResponse response = httpclient.execute(httpPost)) {
            log.debug("POST request returned {}", response.getStatusLine().toString());
            statusCode = response.getStatusLine().getStatusCode();
        } catch (IOException e) {
            log.debug("Could not submit metrics to Confluent: {}", e.getMessage());
        }
    } else {
        statusCode = HttpStatus.SC_BAD_REQUEST;
    }
    return statusCode;
}

From source file:org.eclipse.cbi.common.signing.Signer.java

public static void signFile(File source, File target, String signerUrl)
        throws IOException, MojoExecutionException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(signerUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("file", new FileBody(source));
    post.setEntity(builder.build());//from  w w w.j a  v  a  2s.co m

    HttpResponse response = client.execute(post);
    int statusCode = response.getStatusLine().getStatusCode();

    HttpEntity resEntity = response.getEntity();

    if (statusCode >= 200 && statusCode <= 299 && resEntity != null) {
        InputStream is = resEntity.getContent();
        try {
            FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target);
        } finally {
            IOUtil.close(is);
        }
    } else if (statusCode >= 500 && statusCode <= 599) {
        InputStream is = resEntity.getContent();
        String message = IOUtil.toString(is, "UTF-8");
        throw new NoHttpResponseException("Server failed with " + message);
    } else {
        throw new MojoExecutionException("Signer replied " + response.getStatusLine());
    }
}

From source file:com.liferay.mobile.android.http.file.UploadUtil.java

protected static HttpEntity getMultipartEntity(HttpPostHC4 request, JSONObject parameters) throws Exception {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    Iterator<String> it = parameters.keys();

    while (it.hasNext()) {
        String key = it.next();//  w ww  .  j a v  a 2s. c o  m
        Object value = parameters.get(key);

        ContentBody contentBody;

        if (value instanceof UploadData) {
            UploadData wrapper = (UploadData) value;
            wrapper.setRequest(request);

            contentBody = wrapper;
        } else {
            contentBody = new StringBody(value.toString(), contentType);
        }

        builder.addPart(key, contentBody);
    }

    return builder.build();
}

From source file:com.lexmark.saperion.services.PutFileToSaperionECM.java

private static HttpEntity buildMultipart(String base64FileString, String fileName) throws IOException {
    String indexString = "indexName";
    StringBuilder jsonString = new StringBuilder();
    jsonString.append(setECMRequest(indexString, fileName));
    StringBody jsonBody = new StringBody(jsonString.toString(), ContentType.TEXT_PLAIN);

    FormBodyPart jsonBodyPart = new FormBodyPart("body", jsonBody);
    jsonBodyPart.addField("Content-Type", "application/json; charset=UTF-8");
    jsonBodyPart.addField("Content-ID", "body");

    StringBuilder fileBuilder = new StringBuilder();
    fileBuilder.append(base64FileString);
    StringBody fileBody = new StringBody(fileBuilder.toString(), ContentType.TEXT_PLAIN);

    FormBodyPart fileBodyPart = new FormBodyPart("filePart", fileBody);
    fileBodyPart.addField("Content-Type", "image/png");
    fileBodyPart.addField("Content-ID", "<imagefile>");

    MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    multipartBuilder.setMode(HttpMultipartMode.STRICT);
    multipartBuilder.setBoundary("2676ff6efebdb664f8f7ccb34f864e25");
    multipartBuilder.addPart(jsonBodyPart);
    multipartBuilder.addPart(fileBodyPart);

    /*ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipartBuilder.build().writeTo(out);
    out.close();//from w  w  w .ja  va2s  .c o m
    String s = out.toString("UTF-8");
    System.err.println("output IS "+s);*/

    HttpEntity entity = multipartBuilder.build();
    return entity;

}

From source file:org.safegees.safegees.util.HttpUrlConnection.java

public static String performPostFileCall(String requestURL, String userCredentials, File file) {

    String response = null;//from w ww  .  j a  v a2 s  . c  o  m
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
    reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    //reqEntity.addPart("avatar", new FileBody(file, ContentType.MULTIPART_FORM_DATA));
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(requestURL);
    httppost.addHeader(KEY_HEADER_AUTHORIZED, userCredentials);
    httppost.addHeader("ContentType", "image/png");
    httppost.addHeader("Referer", "https://safegees.appspot.com/v1/user/image/upload/");
    httppost.addHeader("Origin", "https://safegees.appspot.com");
    httppost.addHeader("Upgrade-Insecure-Requests", "1");
    httppost.addHeader("User-Agent",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
    reqEntity.addBinaryBody("avatar", file, ContentType.create("image/png"), file.getName());
    httppost.setEntity(reqEntity.build());
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpclient.execute(httppost);
        Log.e("IMAGE", httpResponse.getStatusLine().getStatusCode() + ":"
                + httpResponse.getStatusLine().getReasonPhrase());
        //response = EntityUtils.toString(httpResponse.getEntity());
        response = httpResponse.getStatusLine().getReasonPhrase();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (httpResponse.getStatusLine().getStatusCode() == 200)
        return response;
    return null;
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

private static HttpEntity multipartEntity(String attachmentFileName, InputStream attachmentContent) {
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

    InputStreamBody inputStreamBody;/*from   www .ja v a2 s  . c  o m*/
    if (isNotBlank(attachmentFileName)) {
        inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM, attachmentFileName);
    } else {
        inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM);
    }

    multipartEntityBuilder.addPart("file", inputStreamBody);

    return multipartEntityBuilder.build();
}

From source file:jog.my.memory.gcm.ServerUtilities.java

/**
 * Uploads a file to the server.//  ww  w. j  av  a2 s  .c om
 * @param context - Context of the app where the file is
 * @param serverUrl - URL of the server
 * @param uri - URI of the file
 * @return - response of posting the file to server
 */
public static String postFile(Context context, String serverUrl, Uri uri) { //TODO: Get the location sent up in here too!

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(serverUrl + "/upload");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    //        //Create the FileBody
    //        final File file = new File(uri.getPath());
    //        FileBody fb = new FileBody(file);

    // deal with the file
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Bitmap bitmap = BitmapFactory.decodeFile(getRealPathFromURI(uri, context));
    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream);
    byte[] byteData = byteArrayOutputStream.toByteArray();
    //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this
    ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?)

    builder.addPart("myFile", byteArrayBody);
    builder.addTextBody("foo", "test text");

    HttpEntity entity = builder.build();
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        Log.d(TAG, "The response code was: " + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        Log.d(TAG, "The image was not successfully uploaded.");
    }

    return null;

    //        HttpClient httpclient = new DefaultHttpClient();
    //        HttpPost httppost = new HttpPost(serverUrl+"/postFile.do");
    //
    //        InputStream stream = null;
    //        try {
    //            stream = context.getContentResolver().openInputStream(uri);
    //
    //            InputStreamEntity reqEntity = new InputStreamEntity(stream, -1);
    //
    //            httppost.setEntity(reqEntity);
    //
    //            HttpResponse response = httpclient.execute(httppost);
    //            Log.d(TAG,"The response code was: "+response.getStatusLine().getStatusCode());
    //            if (response.getStatusLine().getStatusCode() == 200) {
    //                // file uploaded successfully!
    //            } else {
    //                throw new RuntimeException("server couldn't handle request");
    //            }
    //            return response.toString();
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //
    //            // handle error
    //        } finally {
    //            try {
    //                stream.close();
    //            }catch(IOException ioe){
    //                ioe.printStackTrace();
    //            }
    //        }
    //        return null;
}

From source file:com.huawei.ais.demo.TokenDemo.java

/**
 * Base64???Token???/*from  w  w w .j  a va2 s  .  c o m*/
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrCustomsFormEnBase64(String token, String formFile) {

    // 1.?????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form";
    Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token) };
    try {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8"));
        multipartEntityBuilder.addPart("file", fileBody);

        // 2.????, POST??
        HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build());
        System.out.println(response);
        String content = IOUtils.toString(response.getEntity().getContent());
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient//from   w  w w .  j  av a  2  s  . c  om
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }

    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL
            + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);

    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}",
            ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody(
            "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}",
            ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);

    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);

    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));

        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {

            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
        // String output = br.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // postInternal(post);
}

From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient/*from  ww w .  j  a  v a 2s  . c  o m*/
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }

    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL
            + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);

    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}",
            ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody(
            "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}",
            ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);

    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);

    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));

        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {

            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
        // String output = br.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

    send(post);
}