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

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

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:com.ibm.devops.dra.PublishTest.java

/**
 * * Send POST request to DLMS back end with the result file
 * @param bluemixToken - the Bluemix token
 * @param contents - the result file// w w w.  ja  va 2s .c  o m
 * @param jobUrl -  the build url of the build job in Jenkins
 * @param timestamp
 * @return - response/error message from DLMS
 */
public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl,
        String timestamp) throws IOException {

    // create http client and post method
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(this.dlmsUrl);

    postMethod = addProxyInformation(postMethod);
    // build up multi-part forms
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (contents != null) {

        File file = new File(root, contents.getName());
        FileBody fileBody = new FileBody(file);
        builder.addPart("contents", fileBody);

        builder.addTextBody("test_artifact", file.getName());
        if (this.isDeploy) {
            builder.addTextBody("environment_name", environmentName);
        }
        //Todo check the value of lifecycleStage
        builder.addTextBody("lifecycle_stage", lifecycleStage);
        builder.addTextBody("url", jobUrl);
        builder.addTextBody("timestamp", timestamp);

        String fileExt = FilenameUtils.getExtension(contents.getName());
        String contentType;
        switch (fileExt) {
        case "json":
            contentType = CONTENT_TYPE_JSON;
            break;
        case "xml":
            contentType = CONTENT_TYPE_XML;
            break;
        default:
            return "Error: " + contents.getName() + " is an invalid result file type";
        }

        builder.addTextBody("contents_type", contentType);
        HttpEntity entity = builder.build();
        postMethod.setEntity(entity);
        postMethod.setHeader("Authorization", bluemixToken);
    } else {
        return "Error: File is null";
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(postMethod);
        // parse the response json body to display detailed info
        String resStr = EntityUtils.toString(response.getEntity());
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(resStr);

        if (!element.isJsonObject()) {
            // 401 Forbidden
            return "Error: Upload is Forbidden, please check your org name. Error message: "
                    + element.toString();
        } else {
            JsonObject resJson = element.getAsJsonObject();
            if (resJson != null && resJson.has("status")) {
                return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status");
            } else {
                // other cases
                return String.valueOf(response.getStatusLine());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Send data using HTTP POST method to the server named by vhost
 *
 * @param url address to request on the server
 * @param vhost name of the server at address which should respond. When null, localhost is assumed.
 * @param post data to send (name-value-pairs)
 * @param userName user name for HTTP authentication : only sent when requesting localhost
 * @param password encoded password for HTTP authentication : only sent when requesting localhost
 * @param usegzip if the body should be gzipped
 * @return response body/*from   ww w  .  j a v  a 2  s . c o  m*/
 * @throws IOException when an error occurred
 */
public byte[] POSTbytes(final MultiProtocolURL url, final String vhost, final Map<String, ContentBody> post,
        final String userName, final String password, final boolean usegzip, final boolean concurrent)
        throws IOException {
    final HttpPost httpPost = new HttpPost(url.toNormalform(true));
    final boolean localhost = Domains.isLocalhost(url.getHost());
    if (!localhost)
        setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service
    if (vhost == null)
        setHost(Domains.LOCALHOST);

    final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    for (final Entry<String, ContentBody> part : post.entrySet())
        entityBuilder.addPart(part.getKey(), part.getValue());
    final HttpEntity multipartEntity = entityBuilder.build();
    // statistics
    this.upbytes = multipartEntity.getContentLength();

    if (usegzip) {
        httpPost.setEntity(new GzipCompressingEntity(multipartEntity));
    } else {
        httpPost.setEntity(multipartEntity);
    }

    if (!localhost || password == null) {
        return getContentBytes(httpPost, Integer.MAX_VALUE, concurrent);
    }

    byte[] content = null;

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", url.getPort()),
            new UsernamePasswordCredentials(userName, password));

    /* Use the custom YaCyDigestScheme for HTTP Digest Authentication */
    final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new YaCyDigestSchemeFactory()).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).build();

    try {
        this.httpResponse = httpclient.execute(httpPost);
        try {
            HttpEntity httpEntity = this.httpResponse.getEntity();
            if (httpEntity != null) {
                if (getStatusCode() == HttpStatus.SC_OK) {
                    content = getByteArray(httpEntity, Integer.MAX_VALUE);
                }
                // Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
                EntityUtils.consume(httpEntity);
            }
        } finally {
            this.httpResponse.close();
        }
    } finally {
        httpclient.close();
    }
    return content;
}

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * @param reqEntity/*  w  w  w .j  a  v a 2  s. c  om*/
 * @param params
 * @param charset
 */
public void buildParameters(MultipartEntityBuilder reqEntity, Map<String, String> params, Charset charset) {

    if (params != null && !params.isEmpty()) {

        ContentType contentType = ContentType.TEXT_PLAIN.withCharset(charset);

        for (Map.Entry<String, String> entry : params.entrySet()) {

            if (entry.getKey() == null)
                continue;

            String value = entry.getValue();

            if (value == null)
                value = "";

            reqEntity.addPart(entry.getKey(), new StringBody(value, contentType));
        }
    }
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormParamWithMultipart() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();/*  ww  w  .  j  av a2  s  .  c om*/
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

/**
 * attach log using run id/* w w w  .jav  a2  s .  c o m*/
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog");

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

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

/**
 * attach log using run id//  w  w  w. jav a2  s . com
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @param serviceUrl
 * @param scope
 * @return
 */
public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog");

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

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormDataParamWithSimpleRequest() throws IOException, URISyntaxException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formDataParam", HttpMethod.POST);
    String rawData = "name=wso2&age=10";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }//from w  w w  .  jav  a2 s  .  c om

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");

    // Send multipart/form-data request
    connection = request("/test/v1/formDataParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void tesFormParamWithCollection() throws IOException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }/*from w ww  .  j  av  a2s . com*/

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");

    // Send multipart/form-data request
    connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "3");

    // Send x-form-url-encoded request
    connection = request("/test/v1/formParamWithSet", HttpMethod.POST);
    rawData = "names=WSO2&names=IBM&names=IBM";
    encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");

    // Send multipart/form-data request
    connection = request("/test/v1/formParamWithSet", HttpMethod.POST);
    builder = MultipartEntityBuilder.create();
    builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN));
    build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "3");
}

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public int post(String url, Map<String, Object> data, PostType dataType, String charset, String referrer) {
    clearPreviousRequest();//www.j  av  a2 s .  co m

    HttpPost request = new HttpPost(url);
    HttpEntity entity = null;

    if (charset == null) {
        charset = "utf-8";
    }

    Charset detectedCharset = null;
    try {
        detectedCharset = Charset.forName(charset);
    } catch (Exception ex) {
        LOG.warn("invalid charset name {}, switching to utf-8");
        detectedCharset = Charset.forName("utf-8");
    }

    data = handleUnsupportedEncoding(data, detectedCharset);

    switch (dataType) {
    case URL_ENCODED:
        List<NameValuePair> formparams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String) {
                formparams.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
            } else {
                LOG.warn("trying to url encode non string data");
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        try {
            entity = new UrlEncodedFormEntity(formparams, detectedCharset);
        } catch (Exception ex) {
            statusCode = -1;
            exception = ex;
            return statusCode;
        }
        break;

    case MULTIPART:
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(detectedCharset)
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        ContentType formDataCT = ContentType.create("form-data", detectedCharset);
        //                formDataCT = ContentType.DEFAULT_TEXT;

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue() instanceof String) {
                builder = builder.addTextBody(key, (String) entry.getValue(), formDataCT);
            } else if (entry.getValue() instanceof byte[]) {
                builder = builder.addBinaryBody(key, (byte[]) entry.getValue());
            } else if (entry.getValue() instanceof ContentBody) {
                builder = builder.addPart(key, (ContentBody) entry.getValue());
            } else {
                exception = new UnsupportedOperationException(
                        "unssuported body type " + entry.getValue().getClass());
                return statusCode = -1;
            }
        }

        entity = builder.build();
        break;

    default:
        exception = new UnsupportedOperationException("unspported PostType " + dataType);
        return statusCode = -1;
    }

    request.setEntity(entity);
    if (referrer != null) {
        request.addHeader("Referer", referrer);
    }
    return request(request);
}