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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Upload metadata file.//from  w  w  w  .j av a  2s. co  m
 *
 * @param endPoint the end point
 * @param xml the xml
 * @param client the client (optional)
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException the JSON exception
 */
private static String uploadMetadataFile(String endPoint, InputStream xml, CloseableHttpClient client)
        throws IOException, JSONException {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpPost request = new HttpPost(endPoint + TestObjects_URL + "?action=upload");

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("fileupload", xml, ContentType.TEXT_XML, "file.xml");
        HttpEntity entity = builder.build();

        request.setEntity(entity);

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);
            JSONObject jsonRoot = new JSONObject(body);
            return jsonRoot.getJSONObject("testObject").getString("id");
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestObjects_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

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();//  ww w.j  a va  2  s  .  c om
    String s = out.toString("UTF-8");
    System.err.println("output IS "+s);*/

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

}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static void uploadImage(File img) {

    try {/* w ww .j a  va  2  s . co  m*/
        HttpClient httpclient = HttpClientBuilder.create().build();

        ProjectProperties props = new ProjectProperties();
        String endpoint = "http://" + props.get("socket") + props.get("restEndpoint") + "/image/create";
        HttpPost httppost = new HttpPost(endpoint);

        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
        ContentBody cbFile = new FileBody(img, ContentType.MULTIPART_FORM_DATA, img.getName());
        mpEntity.addTextBody("fileName", img.getName());
        mpEntity.addTextBody("description", "File uploaded via Photoshare Desktop Cliend on "
                + new SimpleDateFormat("HH:mm dd/MM/yyyy").format(Calendar.getInstance().getTime()));

        mpEntity.addPart("fileUpload", cbFile);

        httppost.setHeader("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());

        httppost.setEntity(mpEntity.build());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
            EntityUtils.consume(resEntity);
        }

        httppost.releaseConnection();
    } catch (IOException ex) {
        Logger.getLogger(ImageHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * Trains the ranker using the trainingdata.csv
 * /*from  w  w w  .j a va  2  s.c  om*/
 * @param ranker_url URL associated with the ranker Ex.)
 *        "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers"
 * @param rankerName The name of the ranker, to be sent as metadata
 * @param client {@link HttpClient} to send the request to
 * @param training_file Path to the trainingdata.csv
 * @return JSON of the result: { "name": "example-ranker", "url":
 *         "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers/6C76AF-ranker-43",
 *         "ranker_id": "6C76AF-ranker-43", "created": "2015-09-21T18:01:57.393Z", "status":
 *         "Training", "status_description":
 *         "The ranker instance is in its training phase, not yet ready to accept requests" }
 * @throws IOException
 */
public static String trainRanker(String ranker_url, String rankerName, HttpClient client,
        StringBuffer training_data) throws IOException {
    // Create a POST request
    HttpPost post = new HttpPost(ranker_url);
    MultipartEntityBuilder postParams = MultipartEntityBuilder.create();

    // Add data
    String metadata = "\"" + rankerName + "\"";
    StringBody metadataBody = new StringBody(metadata, ContentType.TEXT_PLAIN);
    postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_DATA_LABEL,
            new AnswerFileBody(training_data.toString()));
    postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_METADATA_LABEL, metadataBody);
    post.setEntity(postParams.build());

    // Obtain and parse response
    HttpResponse response = client.execute(post);
    String result = getHttpResultString(response);
    return result;
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * post//  ww  w.j a va 2s .c o  m
 *
 * @param uri
 * @param map
 * @return
 */
public static String post(String uri, Map<String, Object> map) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    HttpEntity httpEntity = null;
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value != null && value instanceof String) {
            String param = (String) value;
            multipartEntityBuilder.addTextBody(key, param, ContentType.create("text/plain", CHARSET));
        }
        if (value != null && value instanceof File) {
            multipartEntityBuilder.addBinaryBody(key, (File) value);
        }
    }
    try {
        httpPost.setEntity(multipartEntityBuilder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
        }
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    try {
        return EntityUtils.toString(httpEntity, CHARSET);
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:org.rapidoid.http.HTTP.java

public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data,
        Map<String, String> files) throws IOException, ClientProtocolException {

    headers = U.safe(headers);//from   ww w  .j a v  a2s  .  co  m
    data = U.safe(data);
    files = U.safe(files);

    CloseableHttpClient client = client(uri);

    try {
        HttpPost httppost = new HttpPost(uri);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        for (Entry<String, String> entry : files.entrySet()) {
            ContentType contentType = ContentType.create("application/octet-stream");
            String filename = entry.getValue();
            File file = IO.file(filename);
            builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename);
        }

        for (Entry<String, String> entry : data.entrySet()) {
            ContentType contentType = ContentType.create("text/plain", "UTF-8");
            builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType);
        }

        httppost.setEntity(builder.build());

        for (Entry<String, String> e : headers.entrySet()) {
            httppost.addHeader(e.getKey(), e.getValue());
        }

        Log.info("Starting HTTP POST request", "request", httppost.getRequestLine());

        CloseableHttpResponse response = client.execute(httppost);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode);

            InputStream resp = response.getEntity().getContent();
            return IOUtils.toByteArray(resp);

        } finally {
            response.close();
        }
    } finally {
        client.close();
    }
}

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();/*from   w w  w.  j ava2  s  .  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:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient//from   ww  w . ja  v  a 2  s.com
 *            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:com.huawei.ais.demo.TokenDemo.java

/**
 * Base64???Token???/*from w  ww.  j  a  va2s . c om*/
 * @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.NetworkUtils.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient//  w  w  w . ja  v  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();
    }

    send(post);
}