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.wisdom.framework.vertx.FormTest.java

@Test
public void testFormSubmissionAsMultipart() throws InterruptedException, IOException {
    Router router = prepareServer();/* w  w w . j a v  a2 s  . c o  m*/

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result submit() {
            final Map<String, List<String>> form = context().form();
            // String
            if (!form.get("key").get(0).equals("value")) {
                return badRequest("key is not equals to value");
            }

            // Multiple values
            List<String> list = form.get("list");
            if (!(list.contains("1") && list.contains("2"))) {
                return badRequest("list does not contains 1 and 2");
            }

            return ok(context().header(HeaderNames.CONTENT_TYPE));
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "submit");
    when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class)))
            .thenReturn(route);

    server.start();
    waitForStart(server);

    int port = server.httpPort();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("key", "value", ContentType.TEXT_PLAIN).addTextBody("list", "1", ContentType.TEXT_PLAIN)
            .addTextBody("list", "2", ContentType.TEXT_PLAIN);

    final HttpResponse response = Request.Post("http://localhost:" + port + "/").body(builder.build()).execute()
            .returnResponse();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.MULTIPART);
}

From source file:org.rapidoid.http.HttpClientUtil.java

private static NByteArrayEntity paramsBody(Map<String, Object> data, Map<String, List<Upload>> files) {
    data = U.safe(data);//from w  ww.  ja  va  2 s.com
    files = U.safe(files);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    for (Map.Entry<String, List<Upload>> entry : files.entrySet()) {
        for (Upload file : entry.getValue()) {
            builder = builder.addBinaryBody(entry.getKey(), file.content(), ContentType.DEFAULT_BINARY,
                    file.filename());
        }
    }

    for (Map.Entry<String, Object> entry : data.entrySet()) {
        String name = entry.getKey();
        String value = String.valueOf(entry.getValue());
        builder = builder.addTextBody(name, value, ContentType.DEFAULT_TEXT);
    }

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        builder.build().writeTo(stream);
    } catch (IOException e) {
        throw U.rte(e);
    }

    byte[] bytes = stream.toByteArray();
    return new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);
}

From source file:org.wso2.security.tools.zap.ext.zapwso2jiraplugin.JiraRestClient.java

public static void invokePutMethodWithFile(String auth, String url, String path) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader(IssueCreatorConstants.ATLASSIAN_TOKEN, "nocheck");
    httppost.setHeader(IssueCreatorConstants.ATLASSIAN_AUTHORIZATION, "Basic " + auth);

    File fileToUpload = new File(path);
    FileBody fileBody = new FileBody(fileToUpload);

    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();

    httppost.setEntity(entity);//from   w  ww  .  j  ava2s  .  c  o  m
    CloseableHttpResponse response = null;

    try {
        response = httpclient.execute(httppost);
    } catch (Exception e) {
        log.error("File upload failed when involing the update method with file ");
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            log.error("Exception occured when closing the connection");
        }
    }
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        Charset charset = contentType != null ? contentType.getCharset() : null;
        httpEntity = new UrlEncodedFormEntity(list, charset);
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }//from   ww  w . j  a v a  2 s . c  o  m
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

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

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("composeRAxMLCommand")) {

        MultipartEntityBuilder arguments = MultipartEntityBuilder.create();
        StringBuffer sb = new StringBuffer();
        getArguments(arguments, sb, "fileName", proteinModelField.getText(), dnaModelField.getText(),
                otherOptionsField.getText(), bootStrapRepsField.getValue(), bootstrapSeed,
                numRunsField.getValue(), outgroupTaxSetString, null, false);
        String command = externalProcRunner.getExecutableCommand() + arguments.toString();
        commandLabel.setText("This command will be used by CIPRes to run RAxML:");
        commandField.setText(command);/*from  ww w .  ja  v  a2 s  .  co  m*/
    } else if (e.getActionCommand().equalsIgnoreCase("clearCommand")) {
        commandField.setText("");
        commandLabel.setText("");
    }
}

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   www  .ja va2  s. c  o  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:net.yacy.grid.http.ClientConnection.java

/**
 * POST request//from w w w  .  j av  a  2s  .  c  o m
 * @param urlstring
 * @param map
 * @param useAuthentication
 * @throws ClientProtocolException 
 * @throws IOException
 */
public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication)
        throws ClientProtocolException, IOException {
    this.request = new HttpPost(urlstring);
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (Map.Entry<String, byte[]> entry : map.entrySet()) {
        entityBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }
    ((HttpPost) this.request).setEntity(entityBuilder.build());
    this.request.setHeader("User-Agent",
            ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    this.init();
}

From source file:io.undertow.servlet.test.security.basic.ServletCertAndDigestAuthTestCase.java

@Test
public void testMultipartRequest() throws Exception {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 2000; i++) {
        sb.append("0123456789");
    }/*from  w  ww . j  a  v  a 2  s  . c  o m*/

    try (TestHttpClient client = new TestHttpClient()) {
        // create POST request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt"));
        builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML));
        HttpEntity entity = builder.build();

        client.setSSLContext(clientSSLContext);
        String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart";
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64
                .encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false));

        HttpResponse result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    }
}

From source file:apimanager.ZohoReportsAPIManager.java

public boolean postBulkJSONImport(JSONObject urlParams, JSONObject postParams) throws IOException {
    //CloseableHttpClient httpclient = HttpClients.createDefault();
    loggerObj.log(Level.INFO, "Inisde postBulkJSONImport");
    JSONObject httpPostObjectParams = new JSONObject();

    String emailaddr = (String) urlParams.get("URLEmail");
    String dbName = (String) urlParams.get("DBName");
    String tableName = (String) urlParams.get("TableName");
    String authToken = (String) urlParams.get(AUTHTOKEN);
    String url = "https://reportsapi.zoho.com/api/" + emailaddr + "/" + URLEncoder.encode(dbName, "UTF-8") + "/"
            + URLEncoder.encode(tableName, "UTF-8")
            + "?ZOHO_ACTION=IMPORT&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=" + authToken
            + "&ZOHO_API_VERSION=1.0";

    loggerObj.log(Level.INFO, "url params are:" + url);
    httpPostObjectParams.put("url", url);

    String jsonFileName = (String) postParams.get("jsonFileName");
    FileBody jsonFile = new FileBody(new File(jsonFileName));

    String ZOHO_IMPORT_FILETYPE = (String) postParams.get("ZOHO_IMPORT_FILETYPE");
    String ZOHO_IMPORT_TYPE = (String) postParams.get("ZOHO_IMPORT_TYPE");
    String ZOHO_AUTO_IDENTIFY = (String) postParams.get("ZOHO_AUTO_IDENTIFY");
    String ZOHO_CREATE_TABLE = (String) postParams.get("ZOHO_CREATE_TABLE");
    String ZOHO_ON_IMPORT_ERROR = (String) postParams.get("ZOHO_ON_IMPORT_ERROR");
    String ZOHO_MATCHING_COLUMNS = (String) postParams.get("ZOHO_MATCHING_COLUMNS");
    String ZOHO_DATE_FORMAT = (String) postParams.get("ZOHO_DATE_FORMAT");
    String ZOHO_SELECTED_COLUMNS = (String) postParams.get("ZOHO_SELECTED_COLUMNS");

    loggerObj.log(Level.INFO, "httpPost params are:" + postParams.toJSONString());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("ZOHO_FILE", jsonFile);
    builder.addTextBody("ZOHO_IMPORT_FILETYPE", ZOHO_IMPORT_FILETYPE);
    builder.addTextBody("ZOHO_IMPORT_TYPE", ZOHO_IMPORT_TYPE);
    builder.addTextBody("ZOHO_AUTO_IDENTIFY", ZOHO_AUTO_IDENTIFY);
    builder.addTextBody("ZOHO_CREATE_TABLE", ZOHO_CREATE_TABLE);
    builder.addTextBody("ZOHO_ON_IMPORT_ERROR", ZOHO_ON_IMPORT_ERROR);
    if (ZOHO_MATCHING_COLUMNS != null) {
        builder.addTextBody("ZOHO_MATCHING_COLUMNS", ZOHO_MATCHING_COLUMNS);
    }/*w w w.  ja  v a  2 s. co m*/

    if (ZOHO_SELECTED_COLUMNS != null) {
        builder.addTextBody("ZOHO_SELECTED_COLUMNS", ZOHO_SELECTED_COLUMNS);
    }
    builder.addTextBody("ZOHO_DATE_FORMAT", ZOHO_DATE_FORMAT);

    httpPostObjectParams.put("multiPartEntityBuilder", builder);

    HttpsClient httpsClientObj = new HttpsClient();
    boolean isSuccessfulPost = httpsClientObj.httpsPost(url, builder, null);

    return isSuccessfulPost;
}

From source file:com.welocalize.dispatcherMW.client.Main.java

public static String uploadXLF(String p_fileName, String p_securityCode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(getFunctinURL(TYPE_UPLOAD, p_securityCode, null));

    try {/*from   ww w  .j a v a 2 s.  c  o m*/
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("fileName", new StringBody(p_fileName, ContentType.create("text/plain", Consts.UTF_8)))
                .addPart("file", new FileBody(new File(p_fileName))).build();
        httpPost.setEntity(reqEntity);

        // send the http request and get the http response
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        String jobID = null;
        String msg = EntityUtils.toString(resEntity);
        if (msg.contains("\"jobID\":\"")) {
            int startIndex = msg.indexOf("\"jobID\":\"");
            jobID = msg.substring(startIndex + 9, msg.indexOf(",", startIndex) - 1);
            System.out.println("Create Job: " + jobID + ", wtih file:" + p_fileName);
            return jobID;
        }

        System.out.println(msg);
        return jobID;
    } catch (Exception e) {
        System.out.println("testHTTPClient error. " + e);
    } finally {
        httpPost.releaseConnection();
    }

    return null;
}