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

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

Introduction

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

Prototype

public MultipartEntityBuilder addTextBody(final String name, final String text) 

Source Link

Usage

From source file:core.VirusTotalAPIHelper.java

public static CloseableHttpResponse reScan(String sha256) {
    try {//  w  w w  .j  a  v  a  2s. c o  m
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/rescan");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("apikey", apiKey);
        builder.addTextBody("resource", sha256);
        HttpEntity multipart = builder.build();
        httpsScanFilePost.setEntity(multipart);

        CloseableHttpResponse response = client.execute(httpsScanFilePost);
        return response;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}

From source file:core.VirusTotalAPIHelper.java

public static CloseableHttpResponse getReport(String sha256) {
    try {/*from w  w w.  j  a va2  s  .c o m*/
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/report");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("apikey", apiKey);
        builder.addTextBody("resource", sha256);
        HttpEntity multipart = builder.build();
        httpsScanFilePost.setEntity(multipart);

        CloseableHttpResponse response = client.execute(httpsScanFilePost);
        return response;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}

From source file:core.VirusTotalAPIHelper.java

public static CloseableHttpResponse scanFile(File fileToScan) {
    if (apiKey == null || apiKey.isEmpty()) {
        return null;
    }/*from  w w w  .  j a  v  a  2 s  . co  m*/
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/scan");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("apikey", apiKey);
        builder.addBinaryBody("file", fileToScan, ContentType.APPLICATION_OCTET_STREAM, fileToScan.getName());
        HttpEntity multipart = builder.build();
        httpsScanFilePost.setEntity(multipart);

        CloseableHttpResponse response = client.execute(httpsScanFilePost);
        return response;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}

From source file:io.confluent.support.metrics.utils.WebClient.java

/**
 * Sends a POST request to a web server//ww w.jav a2 s . c o m
 * @param customerId: customer Id on behalf of which the request is sent
 * @param bytes: request payload
 * @param httpPost: A POST request structure
 * @return an HTTP Status code
 */
public static int send(String customerId, byte[] bytes, HttpPost httpPost) {
    int statusCode = DEFAULT_STATUS_CODE;
    if (bytes != null && bytes.length > 0 && httpPost != null && customerId != null) {

        // add the body to the request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("cid", customerId);
        builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, "filename");
        httpPost.setEntity(builder.build());

        // set the HTTP config
        final RequestConfig config = RequestConfig.custom().setConnectTimeout(requestTimeoutMs)
                .setConnectionRequestTimeout(requestTimeoutMs).setSocketTimeout(requestTimeoutMs).build();

        // send request
        try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
                .build(); CloseableHttpResponse response = httpclient.execute(httpPost)) {
            log.debug("POST request returned {}", response.getStatusLine().toString());
            statusCode = response.getStatusLine().getStatusCode();
        } catch (IOException e) {
            log.debug("Could not submit metrics to Confluent: {}", e.getMessage());
        }
    } else {
        statusCode = HttpStatus.SC_BAD_REQUEST;
    }
    return statusCode;
}

From source file:org.activiti.rest.content.service.api.HttpMultipartHelper.java

public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream,
        Map<String, String> additionalFormFields) throws IOException {

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
        for (Entry<String, String> field : additionalFormFields.entrySet()) {
            entityBuilder.addTextBody(field.getKey(), field.getValue());
        }//www  .j  a v  a  2  s  .c om
    }

    entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType),
            fileName);

    return entityBuilder.build();
}

From source file:me.ixfan.wechatkit.util.HttpClientUtil.java

/**
 * POST data using the Content-Type <code>multipart/form-data</code>.
 * This enables uploading of binary files etc.
 *
 * @param url URL of request./*  w  ww.  j av  a  2 s.c  o m*/
 * @param textInputs Name-Value pairs of text inputs.
 * @param binaryInputs Name-Value pairs of binary files inputs.
 * @return JSON object of response.
 * @throws IOException If I/O error occurs.
 */
public static JsonObject sendMultipartRequestAndGetJsonResponse(String url, Map<String, String> textInputs,
        Map<String, MultipartInput> binaryInputs) throws IOException {
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    if (null != textInputs) {
        textInputs.forEach((k, v) -> multipartEntityBuilder.addTextBody(k, v));
    }
    if (null != binaryInputs) {
        binaryInputs.forEach((k, v) -> {
            if (null == v.getDataBytes()) {
                multipartEntityBuilder.addBinaryBody(k, v.getFile(), v.getContentType(), v.getFile().getName());
            } else {
                multipartEntityBuilder.addBinaryBody(k, v.getDataBytes(), v.getContentType(), v.getFilename());
            }
        });
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setEntity(multipartEntityBuilder.build());
    return httpClient.execute(post, new JsonResponseHandler());
}

From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java

static void getAuthCode() {
    access_token = null;//w  ww.  j  a  v  a 2  s  . c  o m
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("refresh.txt").delete();

    if (gProps == null) {
        initGProps();
    }

    // Contact google for a user code
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code";

        HttpPost codeRequest = new HttpPost(codeUri);

        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
        meb.addTextBody("client_id", gProps.client_id);
        meb.addTextBody("scope", "email profile");
        HttpEntity reqEntity = meb.build();

        codeRequest.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(codeRequest);
        try {

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseJSON = EntityUtils.toString(resEntity);
                    ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                    device_code = root.get("device_code").asText();
                    user_code = root.get("user_code").asText();
                    verification_url = root.get("verification_url").asText();
                    expires_in = root.get("expires_in").asInt();
                }
            } else {
                log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            response.close();
            httpclient.close();
        }
    } catch (IOException e) {
        log.error("Error reading sead-google.json or making http requests for code.");
        log.error(e.getMessage());
    }
}

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

public static void uploadImage(File img) {

    try {// w w  w. j a va 2 s  . c o m
        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);
    }
}

From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java

static void getTokensFromCode() {
    access_token = null;// w  ww  . j  a  v  a 2s.c o m
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("refresh.txt").delete();

    if (gProps == null) {
        initGProps();
    }
    // Query for token now that user has gone through browser part
    // of
    // flow
    HttpPost tokenRequest = new HttpPost(gProps.token_uri);

    MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create();
    tokenRequestParams.addTextBody("client_id", gProps.client_id);
    tokenRequestParams.addTextBody("client_secret", gProps.client_secret);
    tokenRequestParams.addTextBody("code", device_code);
    tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0");

    HttpEntity reqEntity = tokenRequestParams.build();

    tokenRequest.setEntity(reqEntity);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(tokenRequest);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String responseJSON = EntityUtils.toString(resEntity);
                ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                access_token = root.get("access_token").asText();
                refresh_token = root.get("refresh_token").asText();
                token_start_time = System.currentTimeMillis() / 1000;
                expires_in = root.get("expires_in").asInt();
            }
        } else {
            log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

From source file:com.sugarcrm.candybean.webservices.WS.java

/**
 * Private helper method to abstract creating a POST/PUT request.
 * Side Effect: Adds the body to the request
 *
 * @param request     A PUT or POST request
 * @param body        Map of Key Value pairs
 * @param contentType The intended content type of the body
 *//*from  w  ww  .jav a  2s . c  o  m*/
protected static void addBodyToRequest(HttpEntityEnclosingRequestBase request, Map<String, Object> body,
        ContentType contentType) {
    if (body != null) {
        if (contentType == ContentType.MULTIPART_FORM_DATA) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (Map.Entry<String, Object> entry : body.entrySet()) {
                builder.addTextBody(entry.getKey(), (String) entry.getValue());
            }
            request.setEntity(builder.build());
        } else {
            JSONObject jsonBody = new JSONObject(body);
            StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON);
            request.setEntity(strBody);
        }
    }
}