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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:org.eluder.coveralls.maven.plugin.httpclient.CoverallsClient.java

public CoverallsResponse submit(final File file) throws ProcessingException, IOException {
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("json_file", file, MIME_TYPE, FILE_NAME).build();
    HttpPost post = new HttpPost(coverallsUrl);
    post.setEntity(entity);//w w w  .  j  ava 2  s .c  o m
    HttpResponse response = httpClient.execute(post);
    return parseResponse(response);
}

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);// w w  w . j ava  2s.  c o  m
    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:org.olat.test.rest.RepositoryRestClient.java

public RepositoryEntryVO deployResource(File archive, String resourcename, String displayname)
        throws URISyntaxException, IOException {
    RestConnection conn = new RestConnection(deploymentUrl);
    assertTrue(conn.login(username, password));

    URI request = UriBuilder.fromUri(deploymentUrl.toURI()).path("restapi").path("repo").path("entries")
            .build();// ww  w.  j a v a  2s .  c  o  m
    HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
    String softKey = UUID.randomUUID().toString();
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", archive, ContentType.APPLICATION_OCTET_STREAM, archive.getName())
            .addTextBody("filename", archive.getName()).addTextBody("resourcename", resourcename)
            .addTextBody("displayname", displayname).addTextBody("access", "3").addTextBody("softkey", softKey)
            .build();
    method.setEntity(entity);

    HttpResponse response = conn.execute(method);
    assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);

    RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class);
    assertNotNull(vo);
    assertNotNull(vo.getDisplayname());
    assertNotNull(vo.getKey());
    return vo;
}

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);//from w  ww  .j a v  a2s .  c om
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java

@Test
public void httpFilePostTest() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpClient client = builder.build();

    URI url = makeURI();//from  w  w  w . j ava  2 s . c  om
    HttpPost post = new HttpPost(url);

    File file = new File(samplesDir, "/http-file/log.txt");
    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setFile(file);
    entityBuilder.setContentType(ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
    builder2.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext"); // NON-NLS
    HttpEntity multipart = builder2.build();

    post.setEntity(multipart);

    final HttpResponse returned = client.execute(post);
    assertNotNull(returned);

}

From source file:org.retrostore.data.BlobstoreWrapperImpl.java

@Override
public void addScreenshot(String appId, byte[] data, Responder.ContentType contentType, String cookie) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(appId), "'appId' missing");
    Preconditions.checkArgument(data != null && data.length > 0, "'data' is empty");
    Preconditions.checkNotNull(contentType, "'contentType' missing");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(cookie), "'cookie' missing");

    LOG.info(String.format("About to add a screenshot blob of size %d with type %s.", data.length,
            contentType.str));// w w w.j a  va  2  s .c o m

    final String PATH_UPLOAD = "/screenshotUpload";
    String forwardTo = PATH_UPLOAD + "?appId=" + appId;

    LOG.info("Forward to: " + forwardTo);
    String uploadUrl = createUploadUrl(forwardTo);
    LOG.info("UploadUrl: " + uploadUrl);

    // It is important that we set the cookie so that we're authenticated. We do not allow
    // anonymous requests to upload screenshots.
    HttpPost post = new HttpPost(uploadUrl);
    post.setHeader("Cookie", cookie);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Note we need to use the deprecated constructor so we can use our content type.
    builder.addPart("file", new ByteArrayBody(data, contentType.str, "screenshot"));

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

    HttpClient client = HttpClientBuilder.create().build();
    try {
        LOG.info("POST constructed. About to make request!");
        HttpResponse response = client.execute(post);
        LOG.info("Request succeeded!");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        LOG.info(new String(out.toByteArray(), "UTF-8"));

    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Cannot make POST request.", e);
    }
}

From source file:nl.mineleni.cbsviewer.jsp.JSPIntegrationTest.java

/**
 * response validatie test tegen validator.nu
 * /*from  w  w w . ja  v a 2  s .c  o  m*/
 * @param response
 *            test object
 * @throws Exception
 *             als er een fout optreedt tijdens de test.
 */
protected void boilerplateValidationTests(final HttpResponse response) throws Exception {

    final String body = new String(EntityUtils.toByteArray(response.getEntity()), "UTF-8");
    assertNotNull("De response body mag geen null zijn.", body);
    assertTrue("Response body dient met juiste prolog te starten.", body.startsWith(RESPONSEPROLOG));

    // online validation
    final HttpPost validatorrequest = new HttpPost(
            /* "http://html5.validator.nu/" */
            "https://validator.nu/");
    final HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT)
            .addTextBody("content", body, ContentType.APPLICATION_XHTML_XML)
            .addTextBody("schema",
                    "http://s.validator.nu/xhtml5-rdfalite.rnc http://s.validator.nu/html5/assertions.sch http://c.validator.nu/all/",
                    ContentType.DEFAULT_TEXT)
            .addTextBody("level", "error", ContentType.DEFAULT_TEXT)
            .addTextBody("parser", "xml", ContentType.DEFAULT_TEXT)
            // .addTextBody("parser", "html5", ContentType.DEFAULT_TEXT)
            .addTextBody("out", "json", ContentType.DEFAULT_TEXT).build();
    validatorrequest.setEntity(entity);
    final HttpResponse validatorresponse = validatorclient.execute(validatorrequest);

    assertThat("Validator response code.", Integer.valueOf(validatorresponse.getStatusLine().getStatusCode()),
            equalTo(SC_OK));

    final String validatorbody = new String(EntityUtils.toByteArray(validatorresponse.getEntity()), "UTF-8");
    LOGGER.debug("validator body:\n" + validatorbody);

    // controle op succes paragraaf in valadator response
    assertTrue("(X)HTML is niet geldig.", validatorbody.contains("<p class=\"success\">"));
}

From source file:com.m3958.apps.anonymousupload.integration.java.FileUploadTest.java

@Test
public void testPostNone() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    Assert.assertTrue(f.exists());/*from ww w .java 2s  .c  om*/

    String c = Request.Post(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .body(MultipartEntityBuilder.create().addTextBody("fn", "abcfn.md").build()).execute()
            .returnContent().asString();

    String url = c.trim();
    Assert.assertEquals("1", url);

    testComplete();
}

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

public static void uploadImage(File img) {

    try {/*from   www.  jav a  2 s  .c  om*/
        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);
    }
}