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:com.m3958.apps.anonymousupload.integration.java.FileUploadTest.java

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

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

    Assert.assertTrue(f.exists());/*from  w  ww . jav a 2s  . c  o  m*/

    String c = Request.Post(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .body(MultipartEntityBuilder.create()
                    .addBinaryBody("afile", f, ContentType.MULTIPART_FORM_DATA, f.getName()).build())
            .execute().returnContent().asString();

    String url = c.trim();
    Assert.assertTrue(url.endsWith(".md"));

    String cc = Request.Get(url).execute().returnContent().asString();
    Assert.assertTrue(cc.contains("vertx runmod"));

    testComplete();
}

From source file:com.ls.http.base.handler.MultipartRequestHandler.java

public MultipartRequestHandler() {
    this.entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
}

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 . jav a  2s  .co  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:com.m3958.vertxio.assetfeed.integration.java.FileUploadTest.java

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

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

    InputStream is = Files.asByteSource(f).openBufferedStream();

    Assert.assertTrue(f.exists());//from  www. j av  a 2 s  . c  o m

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

    String url = c.trim();
    Assert.assertTrue(url.endsWith("abcfn.md"));

    testComplete();
}

From source file:org.wso2.ml.client.MLClient.java

public CloseableHttpResponse createdDataSet(JSONObject datasetConf) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(mlHost + "/api/datasets/");
    httpPost.setHeader(MLConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addPart("description",
            new StringBody(datasetConf.get("description").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("sourceType",
            new StringBody(datasetConf.get("sourceType").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("destination",
            new StringBody(datasetConf.get("destination").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("dataFormat",
            new StringBody(datasetConf.get("dataFormat").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("containsHeader",
            new StringBody(datasetConf.get("containsHeader").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("datasetName",
            new StringBody(datasetConf.get("datasetName").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("version",
            new StringBody(datasetConf.get("version").toString(), ContentType.TEXT_PLAIN));

    File file = new File(mlDatasetPath);
    multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
            datasetConf.get("file").toString());

    httpPost.setEntity(multipartEntityBuilder.build());
    return httpClient.execute(httpPost);

}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//www  .  j a v  a 2  s . co m
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:eu.seaclouds.platform.planner.core.application.agreements.AgreementGenerator.java

public String generateAgreeemntId(String templateDescription, MonitoringInfo monitoringInfo) {
    String result = null;/*from w  ww  .j a v a  2s .  c om*/
    String monitoring = serializeToXml(monitoringInfo);
    Map<String, Object> template = YamlParser.load(templateDescription);

    HttpEntity httpEntity = MultipartEntityBuilder.create().addTextBody("dam", YamlParser.dump(template))
            .addTextBody("rules", monitoring).build();

    String slaInfoResponse = new HttpHelper(slaUrl).postEntity(SLA_GEN_OP, httpEntity);
    checkNotNull(slaInfoResponse, "Error getting SLA info");
    try {
        ApplicationMonitorId applicationMonitoringId = new ObjectMapper().readValue(slaInfoResponse,
                ApplicationMonitorId.class);
        result = applicationMonitoringId.getId();
    } catch (IOException e) {
        log.error("Error AgreementTemplateId during dam generation {}", this);
    }
    return result;
}

From source file:org.metaeffekt.dcc.agent.UnitBasedEndpointUriBuilder.java

public HttpUriRequest buildHttpUriRequest(Commands command, Id<DeploymentId> deploymentId, Id<UnitId> unitId,
        Id<PackageId> packageId, Map<String, byte[]> executionProperties) {
    Validate.isTrue(executionProperties != null && !executionProperties.isEmpty());

    StringBuilder sb = new StringBuilder("/");
    sb.append(PATH_ROOT).append("/");
    sb.append(deploymentId).append("/");
    sb.append("packages").append("/").append(packageId).append("/");
    sb.append("units").append("/").append(unitId).append("/");
    sb.append(command);/*from   w  w w .j  a  v a  2 s .c o  m*/
    String path = sb.toString();

    URIBuilder uriBuilder = createUriBuilder();
    uriBuilder.setPath(path);
    URI uri;
    try {
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpPut put = new HttpPut(uri);

    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    for (Map.Entry<String, byte[]> entry : executionProperties.entrySet()) {
        multipartBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }

    put.setEntity(multipartBuilder.build());
    if (requestConfig != null) {
        put.setConfig(requestConfig);
    }
    return put;
}

From source file:org.apache.juneau.examples.rest.TestMultiPartFormPostsTest.java

@Test
public void testUpload() throws Exception {
    RestClient client = SamplesMicroservice.DEFAULT_CLIENT;
    File f = FileUtils.createTempFile("testMultiPartFormPosts.txt");
    IOPipe.create(new StringReader("test!"), new FileWriter(f)).closeOut().run();
    HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody(f.getName(), f).build();
    client.doPost(URL + "/upload", entity);

    String downloaded = client.doGet(URL + '/' + f.getName() + "?method=VIEW").getResponseAsString();
    assertEquals("test!", downloaded);
}

From source file:com.github.fabienbarbero.flickr.api.CommandArguments.java

public HttpEntity getBody(Map<String, String> additionalParameters) {
    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    for (Parameter param : params) {
        if (!param.internal) {
            if (param.value instanceof File) {
                entity.addBinaryBody(param.key, (File) param.value);
            } else if (param.value instanceof String) {
                entity.addTextBody(param.key, (String) param.value, CT_TEXT);
            }/*  w  w w. j  a va  2  s.  c  o  m*/
        }
    }
    for (Map.Entry<String, String> entry : additionalParameters.entrySet()) {
        entity.addTextBody(entry.getKey(), entry.getValue(), CT_TEXT);
    }

    return entity.build();
}