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

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

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.//from  ww w  .  j  a va 2  s . c om
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:org.camunda.bpm.RestDeployment.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.err.println("No process files specified");
        System.exit(1);/*from w ww  .  j av  a2 s.c om*/
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080/engine-rest/deployment/create");

    StringBody deploymentName = new StringBody("myDeployment", ContentType.TEXT_PLAIN);
    StringBody enableDuplicateFiltering = new StringBody("true", ContentType.TEXT_PLAIN);
    StringBody deployChangedOnly = new StringBody("true", ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("deployment-name", deploymentName)
            .addPart("enable-duplicate-filtering", enableDuplicateFiltering)
            .addPart("deploy-changed-only", deployChangedOnly);

    for (String resource : args) {
        File resourceFile = new File(resource);
        FileBody fileBody = new FileBody(resourceFile);
        builder.addPart(resourceFile.getName(), fileBody);
    }

    HttpEntity httpEntity = builder.build();
    httpPost.setEntity(httpEntity);

    HttpResponse response = httpClient.execute(httpPost);

    logResponse(response);
}

From source file:org.eclipse.dirigible.cli.apis.ImportProjectAPI.java

public static void importProject(RequestConfig config, String url, InputStream in, String filename,
        Map<String, String> headers) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addPart(PART_NAME, new InputStreamBody(in, filename));

    HttpPost postRequest = new HttpPost(url);
    postRequest.setEntity(entityBuilder.build());
    addHeaders(postRequest, headers);/*from ww  w .  j  av a2s.c  o  m*/
    if (config != null) {
        postRequest.setConfig(config);
    }
    executeRequest(httpClient, postRequest);
}

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 ww  . ja v a2 s. c  om*/

    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.questdb.test.tools.HttpTestUtils.java

private static int upload(File file, String url, String schema, StringBuilder response) throws IOException {
    HttpPost post = new HttpPost(url);
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        MultipartEntityBuilder b = MultipartEntityBuilder.create();
        if (schema != null) {
            b.addPart("schema", new StringBody(schema, ContentType.TEXT_PLAIN));
        }/*  w ww  .  ja va 2 s  .  com*/
        b.addPart("data", new FileBody(file));
        post.setEntity(b.build());
        HttpResponse r = client.execute(post);
        if (response != null) {
            InputStream is = r.getEntity().getContent();
            int n;
            while ((n = is.read()) > 0) {
                response.append((char) n);
            }
            is.close();
        }
        return r.getStatusLine().getStatusCode();
    }
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);// www.ja va 2s.c  o  m
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

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

/**
 * Send a post request to the server to rank answers in the csvAnswerData
 * //from ww  w. j  av a 2 s .  com
 * @param client Authorized {@link HttpClient}
 * @param ranker_url URL of the ranker to hit. Ex.)
 *        https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/ rankers/{ranker_id}/rank
 * @param csvAnswerData A string with the answer data in csv form
 * @return JSONObject of the response from the server
 * @throws ClientProtocolException
 * @throws IOException
 * @throws HttpException
 * @throws JSONException
 */
public static JSONObject rankAnswers(CloseableHttpClient client, String ranker_url, String csvAnswerData)
        throws ClientProtocolException, IOException, HttpException, JSONException {

    // If there is no csv data return an empty array
    if (csvAnswerData.trim().equals("")) {
        return new JSONObject("{\"code\":200 , \"answers\" : []}");
    }
    // Create post request to rank answers
    HttpPost post = new HttpPost(ranker_url);
    MultipartEntityBuilder postParams = MultipartEntityBuilder.create();

    // Fill in post request data
    postParams.addPart(RetrieveAndRankConstants.ANSWER_DATA, new AnswerFileBody(csvAnswerData));
    post.setEntity(postParams.build());

    // Send post request and get resulting response
    HttpResponse response = client.execute(post);
    String responseString = RankerCreationUtil.getHttpResultString(response);
    JSONObject responseJSON = null;
    try {
        responseJSON = (JSONObject) JSON.parse(responseString);
    } catch (NullPointerException | JSONException e) {
        logger.error(e.getMessage());
    }
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new HttpException(responseString + ":" + post);
    }
    return responseJSON;
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

/**
 * This method is use to post data in multidata format
 * @param url//from www  .ja v a2s.co  m
 *          - backend url
 * @param mobileApplicationBean
 *          - Bean class of the mobile application
 * @param headers
 *          - header files
 */
public static String doPostMultiData(String url, MobileApplicationBean mobileApplicationBean,
        Map<String, String> headers) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    // initializing headers
    if (headers != null && headers.size() > 0) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            httpPost.setHeader(key, headers.get(key));
        }
    }
    MultipartEntityBuilder reqEntity;
    reqEntity = MultipartEntityBuilder.create();
    reqEntity.addPart("version",
            new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("provider",
            new StringBody(mobileApplicationBean.getProvider(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("markettype",
            new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("platform",
            new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("description",
            new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA));
    FileBody bannerImageFile = new FileBody(mobileApplicationBean.getBannerFilePath());
    reqEntity.addPart("bannerFile", bannerImageFile);
    FileBody iconImageFile = new FileBody(mobileApplicationBean.getIconFile());
    reqEntity.addPart("iconFile", iconImageFile);
    FileBody screenShot1 = new FileBody(mobileApplicationBean.getScreenShot1File());
    reqEntity.addPart("screenshot1File", screenShot1);
    FileBody screenShot2 = new FileBody(mobileApplicationBean.getScreenShot2File());
    reqEntity.addPart("screenshot2File", screenShot2);
    FileBody screenShot3 = new FileBody(mobileApplicationBean.getScreenShot3File());
    reqEntity.addPart("screenshot3File", screenShot3);
    reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("mobileapp",
            new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("sso_ssoProvider",
            new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("appmeta",
            new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA));

    final HttpEntity entity = reqEntity.build();
    httpPost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = "";
    try {
        responseBody = httpClient.execute(httpPost, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseBody;
}

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

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

    // postInternal(post);
}

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

/**
 * Trains the ranker using the trainingdata.csv
 * /*ww  w  .  ja  v  a  2  s  .  co m*/
 * @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;
}