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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:erainformatica.utility.JSONHelper.java

public static TelegramRequestResult<JSONObject> readJsonFromUrl(String url, InputFile file) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(url);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
    builder.addBinaryBody(file.getName(), file.getFile_content(), ContentType.APPLICATION_OCTET_STREAM,
            file.getName() + "." + file.getExtension());
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);/*w w  w.j a  v a 2s  .com*/

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(uploadFile);
    } catch (IOException ex) {
        Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpEntity responseEntity = response.getEntity();

    try {
        return readJsonFromInputStream(responseEntity.getContent());
    } catch (Exception ex) {
        return new TelegramRequestResult<>(false, ex.toString(), null);
    }

}

From source file:rogerthat.topdesk.bizz.Util.java

public static void uploadFile(String apiUrl, String apiKey, String unid, byte[] content, String contentType,
        String fileName) throws IOException, ParseException {
    URL url = new URL(apiUrl + "/api/incident/upload/" + unid);
    HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30));
    log.info("Uploading attachment of size " + content.length / 1000 + "KB");
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("filename", content,
                    org.apache.http.entity.ContentType.create(contentType), fileName);

    addMultipartBodyToRequest(multipartEntityBuilder.build(), request);
    String authHeader = "TOKEN id=\"" + apiKey + "\"";
    request.addHeader(new HTTPHeader("Authorization", authHeader));
    URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
    HTTPResponse response = urlFetch.fetch(request);
    int responseCode = response.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        String responseContent = getContent(response);
        throw new TopdeskApiException("Uploading image " + fileName + " failed with response code "
                + responseCode + "\nContent:" + responseContent);
    }/*from   w w  w .j a  v a  2s.c o  m*/
}

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

static void getAuthCode() {
    access_token = null;//from  w w  w .j a v  a  2 s .  c om
    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: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 2s  .  c o  m*/
    }

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

    return entityBuilder.build();
}

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  w w  . ja v  a 2  s  .  c om*/
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);
        }
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * Send a post request to the server to rank answers in the csvAnswerData
 * //from  w  w w  .  j  av a 2s .co m
 * @param client Authorized {@link HttpClient}
 * @param ranker_url URL of the ranker to hit. Ex.)
 *        https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/ rankers/{ranker_id}/rank
 * @param csvAnswerData A string with the answer data in csv form
 * @return JSONObject of the response from the server
 * @throws ClientProtocolException
 * @throws IOException
 * @throws HttpException
 * @throws JSONException
 */
public static JSONObject rankAnswers(CloseableHttpClient client, String ranker_url, String csvAnswerData)
        throws ClientProtocolException, IOException, HttpException, JSONException {

    // If there is no csv data return an empty array
    if (csvAnswerData.trim().equals("")) {
        return new JSONObject("{\"code\":200 , \"answers\" : []}");
    }
    // Create post request to rank answers
    HttpPost post = new HttpPost(ranker_url);
    MultipartEntityBuilder postParams = MultipartEntityBuilder.create();

    // Fill in post request data
    postParams.addPart(RetrieveAndRankConstants.ANSWER_DATA, new AnswerFileBody(csvAnswerData));
    post.setEntity(postParams.build());

    // Send post request and get resulting response
    HttpResponse response = client.execute(post);
    String responseString = RankerCreationUtil.getHttpResultString(response);
    JSONObject responseJSON = null;
    try {
        responseJSON = (JSONObject) JSON.parse(responseString);
    } catch (NullPointerException | JSONException e) {
        logger.error(e.getMessage());
    }
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new HttpException(responseString + ":" + post);
    }
    return responseJSON;
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);/*from w w w  . j  a va2 s.co m*/
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:utils.APIImporter.java

private static void addAPIImage(String folderPath, String accessToken, String uuid) {
    File apiFolder = new File(folderPath);
    File[] fileArray = apiFolder.listFiles();
    if (fileArray != null) {
        for (File file : fileArray) {
            String fileName = file.getName();
            String imageName = fileName.substring(0, fileName.indexOf("."));
            if (imageName.equalsIgnoreCase(ImportExportConstants.IMG_NAME)) {
                File imageFile = new File(folderPath + ImportExportConstants.ZIP_FILE_SEPARATOR + fileName);
                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, imageFile);
                HttpEntity entity = multipartEntityBuilder.build();
                String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail";
                CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
                HttpPost request = new HttpPost(url);
                request.setHeader(HttpHeaders.AUTHORIZATION,
                        ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
                request.setEntity(entity);
                try {
                    client.execute(request);
                } catch (IOException e) {
                    errorMsg = "Error occurred while publishing the API thumbnail";
                    log.error(errorMsg, e);
                }/*  w w w.  j ava2 s .  c  o m*/
                break;
            }
        }
    }
}

From source file:utils.APIImporter.java

/**
 * update the content of a document of the API been sent
 * @param folderPath folder path to the imported API
 * @param uuid uuid of the API//from   w  w  w . j av a2 s. c  om
 * @param response payload for the publishing document
 * @param accessToken access token
 */
private static void addDocumentContent(String folderPath, String uuid, String response, String accessToken) {
    String documentId = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_ID);
    String sourceType = ImportExportUtils.readJsonValues(response, ImportExportConstants.SOURCE_TYPE);
    String documentName = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
    String directoryName;
    //setting directory name depending on the document source type
    if (sourceType.equals(ImportExportConstants.INLINE_DOC_TYPE)) {
        directoryName = ImportExportConstants.INLINE_DOCUMENT_DIRECTORY;
    } else {
        directoryName = ImportExportConstants.FILE_DOCUMENT_DIRECTORY;
    }
    //getting document content
    String documentContentPath = folderPath + ImportExportConstants.DIRECTORY_SEPARATOR
            + ImportExportConstants.DOCUMENT_DIRECTORY + ImportExportConstants.DIRECTORY_SEPARATOR
            + directoryName + ImportExportConstants.DIRECTORY_SEPARATOR + documentName;
    File content = new File(documentContentPath);
    HttpEntity entity = null;
    if (sourceType.equals(ImportExportConstants.FILE_DOC_TYPE)) {
        //adding file type content
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, content);
        entity = multipartEntityBuilder.build();
    } else {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(content));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            String inlineContent = sb.toString();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addTextBody(ImportExportConstants.MULTIPART_Inline, inlineContent,
                    ContentType.APPLICATION_OCTET_STREAM);
            entity = multipartEntityBuilder.build();
        } catch (IOException e) {
            errorMsg = "error occurred while retrieving content of document "
                    + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
            log.error(errorMsg, e);
        } finally {
            IOUtils.closeQuietly(br);
        }
    }
    String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId + "/content";
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    HttpPost request = new HttpPost(url);
    request.setHeader(HttpHeaders.AUTHORIZATION,
            ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
    request.setEntity(entity);
    try {
        client.execute(request);
    } catch (IOException e) {
        errorMsg = "error occurred while uploading the content of document "
                + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
        log.error(errorMsg, e);
    }
}

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

static void getTokensFromCode() {
    access_token = null;//from w  ww .j  a  va2s . com
    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();
        }

    }

}