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

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

Introduction

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

Prototype

public MultipartEntityBuilder addTextBody(final String name, final String text) 

Source Link

Usage

From source file:groovyx.net.http.ApacheEncoders.java

/**
 *  Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be
 *  encoded using the encoders available to the {@link ChainedHttpConfig} object.
 *
 * @param config the chained configuration object
 * @param ts the server adapter/*from   w w w  .  java2s .c  o  m*/
 */
public static void multipart(final ChainedHttpConfig config, final ToServer ts) {
    try {
        final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();

        final Object body = request.actualBody();
        if (!(body instanceof MultipartContent)) {
            throw new IllegalArgumentException("Multipart body content must be MultipartContent.");
        }

        final String contentType = request.actualContentType();
        if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0))
                || contentType.equals(MULTIPART_MIXED.getAt(0)))) {
            throw new IllegalArgumentException("Multipart body content must be multipart/form-data.");
        }

        final String boundary = randomString(10);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setBoundary(boundary);

        final String boundaryContentType = "multipart/form-data; boundary=" + boundary;

        entityBuilder.setContentType(ContentType.parse(boundaryContentType));

        for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) {
            if (mpe.getFileName() == null) {
                entityBuilder.addTextBody(mpe.getFieldName(), (String) mpe.getContent());

            } else {
                final byte[] encodedBytes = EmbeddedEncoder.encode(config, mpe.getContentType(),
                        mpe.getContent());
                entityBuilder.addBinaryBody(mpe.getFieldName(), encodedBytes, parse(mpe.getContentType()),
                        mpe.getFileName());
            }
        }

        request.setContentType(boundaryContentType);

        ts.toServer(entityBuilder.build().getContent());

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadAlbumRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from  w ww . ja v a 2  s  . c  o  m
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(File imageFile, String uploadId)
        throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.duracloud.common.web.RestHttpHelperTest.java

@Test
public void testMultipartPost() throws Exception {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("text-part", "text");
    // Note: Including a file as one piece of the multipart body
    // causes this test to fail intermittently. Replacing it here with string bytes.
    builder.addBinaryBody("binary-part", "binary-content".getBytes());
    HttpEntity reqEntity = builder.build();

    HttpResponse response = helper.multipartPost(getUrl(), reqEntity);
    verifyResponse(response);//w ww  .j  ava  2s .c om
}

From source file:org.apache.sling.hapi.client.forms.internal.FormValues.java

public HttpEntity toMultipartEntity() {
    MultipartEntityBuilder eb = MultipartEntityBuilder.create();
    for (NameValuePair p : list.flatten()) {
        eb.addTextBody(p.getName(), p.getValue());
    }//from w ww.j  a  v  a  2  s. co  m
    return eb.build();
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadStoryPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException/*from   w  ww . j  av  a 2s .  c o  m*/
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:eu.seaclouds.platform.dashboard.http.HttpPostRequestBuilder.java

public String build() throws IOException, URISyntaxException {
    if (!params.isEmpty() && entity == null) {
        if (!isMultipart) {
            this.entity = new UrlEncodedFormEntity(params);
        } else {/*from w w w. j  a v  a2s.c o  m*/
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            for (NameValuePair pair : params) {
                entityBuilder.addTextBody(pair.getName(), pair.getValue());
            }

            this.entity = entityBuilder.build();
        }
    }

    URI uri = new URIBuilder().setHost(host).setPath(path).setScheme(scheme).build();

    this.requestBase = new HttpPost(uri);

    for (NameValuePair header : super.headers) {
        requestBase.addHeader(header.getName(), header.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        if (this.entity != null) {
            this.requestBase.setEntity(this.entity);
        }
        return httpClient.execute(requestBase, responseHandler, context);
    }
}

From source file:net.monofraps.gradlecurse.tasks.CurseDeployTask.java

private void uploadArtifact(final Deployment deployment) {
    getLogger().lifecycle("Curse Upload: " + "Uploading to Curse...");
    getLogger().lifecycle("Curse Upload: " + deployment.toString());

    //TODO: binary or app/zip, maybe an option or auto-detect from file extension ?!
    final FileBody fileBody = new FileBody(deployment.getSourceFile(), ContentType.DEFAULT_BINARY,
            deployment.getUploadFileName());

    final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addTextBody("name", deployment.getUploadFileName());
    multipartEntityBuilder.addTextBody("file_type", deployment.getFileType().toString());
    multipartEntityBuilder.addTextBody("change_log", deployment.getChangeLog());
    multipartEntityBuilder.addTextBody("change_markup_type", deployment.getChangeLogMarkup().toString());
    multipartEntityBuilder.addTextBody("known_caveats", deployment.getKnownCaveats());
    multipartEntityBuilder.addTextBody("caveats_markup_type", deployment.getCaveatMarkup().toString());
    multipartEntityBuilder.addPart("file", fileBody);
    multipartEntityBuilder.addTextBody("game_versions", StringUtils.join(deployment.getGameVersions(), ","));

    try {/*from w  w w.  java2s . c o m*/
        final HttpPost httpPost = new HttpPost(probeForRedirect(deployment));
        httpPost.addHeader("User-Agent", "GradleCurse Uploader/1.0");
        httpPost.addHeader("X-API-Key", deployment.getApiKey());
        httpPost.setEntity(multipartEntityBuilder.build());

        final HttpClient httpClient = HttpClientBuilder.create().build();
        final HttpResponse httpResponse = httpClient.execute(httpPost);

        getLogger().lifecycle("Curse Upload: " + httpResponse.getStatusLine());
        getLogger().debug(EntityUtils.toString(httpResponse.getEntity()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException/*from   ww w.  ja va  2s .com*/
 * @throws IOException
 */
protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", bufferedImageToByteArray(imageFile), ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:mesquite.zephyr.GarliRunnerCIPRes.GarliRunnerCIPRes.java

public Object getProgramArguments(String dataFileName, String configFilePath, boolean isPreflight) {
    MultipartEntityBuilder arguments = MultipartEntityBuilder.create();

    arguments.addTextBody("vparam.user_conffile_", "1");
    arguments.addTextBody("vparam.userconffilethere_", "1");
    arguments.addTextBody("vparam.userconffileconfirm_", "1");

    arguments.addTextBody("vparam.searchreps_value_", "" + numRuns);

    return arguments;
}

From source file:com.tur0kk.facebook.FacebookClient.java

public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
        // facebook requires multipart post structure
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("message", msg); // description

        if (placeId != null && !"".equals(placeId)) {
            builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences
        }/*ww  w .j  a  v a2  s  .c  om*/

        // convert image to bytearray and append to multipart
        BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(image, 0, 0, null);
        bGr.dispose();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bimage, "png", baos);
        builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

        // generate multipart byte stream and add to payload of post package
        HttpEntity multipart = builder.build();
        ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream(
                (int) multipart.getContentLength());
        multipart.writeTo(multipartOutStream);
        request.addPayload(multipartOutStream.toByteArray());

        // set header of post package
        Header contentType = multipart.getContentType();
        request.addHeader(contentType.getName(), contentType.getValue());

        // send and response answer
        Response response = request.send();
        return response.getBody();
    } else {
        throw new RuntimeException("message and image needed");
    }
}