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.brunocvcunha.instagram4j.requests.InstagramUploadStoryPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from ww w  .  j a v  a  2 s.co  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:com.redhat.jenkins.plugins.bayesian.Bayesian.java

public BayesianStepResponse submitStackForAnalysis(Collection<FilePath> manifests) throws BayesianException {
    String stackAnalysesUrl = getApiUrl() + "/stack-analyses";
    HttpPost httpPost = new HttpPost(stackAnalysesUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (FilePath manifest : manifests) {
        byte[] content = null;
        try (InputStream in = manifest.read()) {
            content = ByteStreams.toByteArray(in);
            builder.addBinaryBody("manifest[]", content, ContentType.DEFAULT_BINARY, manifest.getName());
        } catch (IOException | InterruptedException e) {
            throw new BayesianException(e);
        } finally {
            content = null;//from www.  j ava  2s.  co  m
        }
    }
    HttpEntity multipart = builder.build();
    builder = null;
    httpPost.setEntity(multipart);
    httpPost.setHeader("Authorization", "Bearer " + getAuthToken());

    BayesianResponse responseObj = null;
    Gson gson;
    try (CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(httpPost)) {
        HttpEntity entity = response.getEntity();
        // Yeah, the endpoint actually returns 200 from some reason;
        // I wonder what happened to the good old-fashioned 202 :)
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new BayesianException("Bayesian error: " + response.getStatusLine().getStatusCode());
        }

        Charset charset = ContentType.get(entity).getCharset();
        try (InputStream is = entity.getContent();
                Reader reader = new InputStreamReader(is,
                        charset != null ? charset : HTTP.DEF_CONTENT_CHARSET)) {
            gson = new GsonBuilder().create();
            responseObj = gson.fromJson(reader, BayesianResponse.class);
            String analysisUrl = stackAnalysesUrl + "/" + responseObj.getId();
            return new BayesianStepResponse(responseObj.getId(), "", analysisUrl, true);
        }
    } catch (IOException e) {
        throw new BayesianException("Bayesian error", e);
    } finally {
        // just to be sure...
        responseObj = null;
        httpPost = null;
        multipart = null;
        gson = null;
    }
}

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   ww w.j a v a  2  s.co  m

    // 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:org.ops4j.pax.web.itest.base.HttpTestClient.java

public void testPostMultipart(String path, Map<String, Object> multipartContent, String expectedContent,
        int httpRC) throws IOException {
    HttpPost httppost = new HttpPost(path);

    httppost.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5");

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for (Entry<String, Object> content : multipartContent.entrySet()) {
        if (content.getValue() instanceof String) {
            multipartEntityBuilder.addPart(content.getKey(),
                    new StringBody((String) content.getValue(), ContentType.TEXT_PLAIN));
        }/*from  w w w .  j  a  v a  2s .  co m*/
    }

    httppost.setEntity(multipartEntityBuilder.build());

    CloseableHttpResponse response = httpclient.execute(httppost, context);

    assertEquals("HttpResponseCode", httpRC, response.getStatusLine().getStatusCode());

    String responseBodyAsString = EntityUtils.toString(response.getEntity());
    if (expectedContent != null) {
        assertTrue("Content: " + responseBodyAsString, responseBodyAsString.contains(expectedContent));
    }
    response.close();
}

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  . j  a  v  a 2  s .  co m*/
 * @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:org.modeshape.web.jcr.rest.AbstractRestTest.java

protected Response doPostMultiPart(String filePath, String elementName, String url, String contentType) {
    try {//from ww w . j  a v  a  2s .  co m

        if (StringUtil.isBlank(contentType)) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }

        url = URL_ENCODER.encode(RestHelper.urlFrom(getServerContext(), url));

        HttpPost post = new HttpPost(url);
        post.setHeader("Accept", MediaType.APPLICATION_JSON);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IoUtil.write(fileStream(filePath), baos);
        entityBuilder.addPart(elementName, new ByteArrayBody(baos.toByteArray(), "test_file"));
        post.setEntity(entityBuilder.build());

        return new Response(post);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
        return null;
    }
}

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/*  www  .java 2s .co 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:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java

protected HttpPost buildCatalogRequest(String fullUri) {
    String boundary = "---------------" + UUID.randomUUID().toString();
    HttpPost post = new HttpPost(fullUri);
    post.addHeader("Accept", "application/json");
    post.addHeader("Content-Type",
            org.apache.http.entity.ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundary);
    post.addHeader("sessionId", this.catalogObjectAction.getSessionId());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);/*from  w  w  w. j a  va2 s.  c om*/
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", new FileBody(this.catalogObjectAction.getNodeSourceJsonFile()));
    builder.addTextBody(COMMIT_MESSAGE_PARAM, this.catalogObjectAction.getCommitMessage());
    if (!this.catalogObjectAction.isRevised()) {
        builder.addTextBody(NAME_PARAM, this.catalogObjectAction.getNodeSourceName());
        builder.addTextBody(KIND_PARAM, this.catalogObjectAction.getKind());
        builder.addTextBody(OBJECT_CONTENT_TYPE_PARAM, this.catalogObjectAction.getObjectContentType());
    }
    post.setEntity(builder.build());
    return post;
}

From source file:com.google.appinventor.components.runtime.MediaStore.java

/**
 * Asks the Web service to store the given media file.
 *
 * @param mediafile The value to store.// w w  w  . j  a va  2  s .  co  m
 */
@SimpleFunction
public void PostMedia(String mediafile) throws FileNotFoundException {
    AsyncCallbackPair<String> myCallback = new AsyncCallbackPair<String>() {
        public void onSuccess(final String response) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    MediaStored(response);
                }
            });
        }

        public void onFailure(final String message) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    WebServiceError(message);
                }
            });
        }
    };

    try {
        HttpClient client = new DefaultHttpClient();

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

        String[] pathtokens = mediafile.split("/");
        String newMediaPath;

        if (pathtokens[0].equals("file:")) {
            newMediaPath = new java.io.File(new URL(mediafile).toURI()).getAbsolutePath();
        } else {
            newMediaPath = mediafile;
        }

        File media = new File(newMediaPath);
        entityBuilder.addPart("file", new FileBody(media));

        HttpEntity entity = entityBuilder.build();

        String uploadURL = getUploadUrl();
        HttpPost post = new HttpPost(uploadURL);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);
        myCallback.onSuccess(result);
    } catch (Exception e) {
        e.printStackTrace();
        myCallback.onFailure(e.getMessage());
    }
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

@VisibleForTesting
String post(HttpRequestBase requestBase //
        , ReturningTextProcessor contentProcessable, HttpAction ha) {
    Post post = (Post) ha;/*  ww  w.jav a  2s .com*/
    Charset charset = Charset.forName(post.getCharset());
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    ImmutableMap<String, Object> postParams = post.getParams();
    for (Map.Entry<String, Object> entry : postParams.entrySet()) {
        applyToEntityBuilder(entry.getKey(), entry.getValue(), charset, entityBuilder);
    }
    ((HttpPost) requestBase).setEntity(entityBuilder.build());

    return executeAndProcess(requestBase, contentProcessable, ha);
}