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:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java

@Override
public DalRequest createForUpload(String url, List<Pair<String, String>> pairs, String rand_num,
        String namesInOrder, String signature, File fileForUpload) {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (Pair<String, String> pair : pairs) {
        builder.addTextBody(pair.a, pair.b);
    }//from w w  w . ja  v  a 2 s. c  o m

    builder.addPart("uploadfile", new FileBody(fileForUpload)).addTextBody("rand_num", rand_num)
            .addTextBody("url", url);

    HttpEntity entity = builder.addTextBody("param_order", namesInOrder).addTextBody("signature", signature)
            .build();

    HttpPost post = new HttpPost(url);
    post.setEntity(entity);

    return new DalRequestImpl(post);
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadVideoRequest.java

/**
 * Create the required multipart entity//from   ww  w .  j ava2  s.co m
 * @param uploadId Session ID
 * @return Entity to submit to the upload
 * @throws ClientProtocolException
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("media_type", "2");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:com.android.tools.idea.diagnostics.crash.CrashReport.java

public void serialize(@NotNull MultipartEntityBuilder builder) {
    builder.addTextBody("type", myType.toString());

    if (productData != null) {
        productData.forEach(builder::addTextBody);
    }/*w  ww  .j  a va2  s.co m*/

    serializeTo(builder);
}

From source file:com.cognifide.qa.bb.aem.content.ContentInstaller.java

/**
 * This method uploads, installs and replicates the package indicated by the name
 * provided as the method's parameter. For each of these actions activateAemPackage constructs
 * and sends a POST request to AEM instance. If any of the POST requests lead to NOK response,
 * activateAemPackage will throw an exception.
 * <br>/*from w  w  w  . j a va2s  . c  o m*/
 * Method will look for content in the location indicated by the content.path property.
 * The content path defaults to "src/main/content".
 *
 * @param packageName Name of the package to be activated.
 * @throws IOException Thrown when AEM instance returns NOK response.
 */
public void activateAemPackage(String packageName) throws IOException {
    HttpPost upload = builder.createUploadRequest();
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addBinaryBody("package", new File(CONTENT_PATH, packageName), ContentType.DEFAULT_BINARY,
            packageName);
    entityBuilder.addTextBody("force", "true");
    upload.setEntity(entityBuilder.build());
    JsonObject result = sender.sendCrxRequest(upload);
    String path = result.get("path").getAsString();

    HttpPost install = builder.createInstallRequest(path);
    sender.sendCrxRequest(install);

    HttpPost replicate = builder.createReplicateRequest(path);

    sender.sendCrxRequest(replicate);
}

From source file:com.ritesh.idea.plugin.util.HttpRequestBuilder.java

private HttpRequestBase getHttpRequest() throws URISyntaxException, UnsupportedEncodingException {
    if (!route.isEmpty()) {
        String path = urlBuilder.getPath() + route;
        path = path.replace("//", "/");
        urlBuilder.setPath(path);//from  w w w . j  a  v  a2s.  c o  m
    }
    request.setURI(urlBuilder.build());
    if (request instanceof HttpPost) {
        if (fileParam != null) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair formParam : formParams) {
                builder.addTextBody(formParam.getName(), formParam.getValue());
            }
            HttpEntity entity = builder
                    .addBinaryBody(fileParam, fileBytes, ContentType.MULTIPART_FORM_DATA, fileName).build();
            ((HttpPost) request).setEntity(entity);
        } else if (!formParams.isEmpty()) {
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(formParams));
        }
    } else if (request instanceof HttpPut) {
        if (!formParams.isEmpty()) {
            ((HttpPut) request).setEntity(new UrlEncodedFormEntity(formParams));
        }
    }
    return request;

}

From source file:com.cognifide.aet.common.TestSuiteRunner.java

private SuiteExecutionResult startSuiteExecution(File testSuite) throws IOException {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("suite", testSuite,
            ContentType.APPLICATION_XML, testSuite.getName());
    if (domain != null) {
        entityBuilder.addTextBody("domain", domain);
    }//from   w  w  w .  jav  a  2 s  .co  m
    HttpEntity entity = entityBuilder.build();
    return Request.Post(getSuiteUrl()).body(entity).connectTimeout(timeout).socketTimeout(timeout).execute()
            .handleResponse(suiteExecutionResponseHandler);
}

From source file:jog.my.memory.gcm.ServerUtilities.java

/**
 * Uploads a file to the server.//from   w  ww  .  jav  a 2s  . c om
 * @param context - Context of the app where the file is
 * @param serverUrl - URL of the server
 * @param uri - URI of the file
 * @return - response of posting the file to server
 */
public static String postFile(Context context, String serverUrl, Uri uri) { //TODO: Get the location sent up in here too!

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(serverUrl + "/upload");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    //        //Create the FileBody
    //        final File file = new File(uri.getPath());
    //        FileBody fb = new FileBody(file);

    // deal with the file
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Bitmap bitmap = BitmapFactory.decodeFile(getRealPathFromURI(uri, context));
    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream);
    byte[] byteData = byteArrayOutputStream.toByteArray();
    //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this
    ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?)

    builder.addPart("myFile", byteArrayBody);
    builder.addTextBody("foo", "test text");

    HttpEntity entity = builder.build();
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        Log.d(TAG, "The response code was: " + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        Log.d(TAG, "The image was not successfully uploaded.");
    }

    return null;

    //        HttpClient httpclient = new DefaultHttpClient();
    //        HttpPost httppost = new HttpPost(serverUrl+"/postFile.do");
    //
    //        InputStream stream = null;
    //        try {
    //            stream = context.getContentResolver().openInputStream(uri);
    //
    //            InputStreamEntity reqEntity = new InputStreamEntity(stream, -1);
    //
    //            httppost.setEntity(reqEntity);
    //
    //            HttpResponse response = httpclient.execute(httppost);
    //            Log.d(TAG,"The response code was: "+response.getStatusLine().getStatusCode());
    //            if (response.getStatusLine().getStatusCode() == 200) {
    //                // file uploaded successfully!
    //            } else {
    //                throw new RuntimeException("server couldn't handle request");
    //            }
    //            return response.toString();
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //
    //            // handle error
    //        } finally {
    //            try {
    //                stream.close();
    //            }catch(IOException ioe){
    //                ioe.printStackTrace();
    //            }
    //        }
    //        return null;
}

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  . jav a 2  s . c  o 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:be.ugent.psb.coexpnetviz.io.JobServer.java

private HttpEntity makeRequestEntity(JobDescription job) throws UnsupportedEncodingException {

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    // Action to request of server
    entityBuilder.addTextBody("__controller", "api");
    entityBuilder.addTextBody("__action", "execute_job");

    // Baits // w  ww.  java 2 s  .c o m
    if (job.getBaitGroupSource() == BaitGroupSource.FILE) {
        entityBuilder.addBinaryBody("baits_file", job.getBaitGroupPath().toFile(), ContentType.TEXT_PLAIN,
                job.getBaitGroupPath().getFileName().toString());
    } else if (job.getBaitGroupSource() == BaitGroupSource.TEXT) {
        entityBuilder.addTextBody("baits", job.getBaitGroupText());
    } else {
        assert false;
    }

    // Expression matrices
    for (Path path : job.getExpressionMatrixPaths()) {
        entityBuilder.addBinaryBody("matrix[]", path.toFile(), ContentType.TEXT_PLAIN, path.toString());
    }

    // Correlation method
    String correlationMethod = null;
    if (job.getCorrelationMethod() == CorrelationMethod.MUTUAL_INFORMATION) {
        correlationMethod = "mutual_information";
    } else if (job.getCorrelationMethod() == CorrelationMethod.PEARSON) {
        correlationMethod = "pearson_r";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("correlation_method", correlationMethod);

    // Cutoffs
    entityBuilder.addTextBody("lower_percentile_rank", Double.toString(job.getLowerPercentile()));
    entityBuilder.addTextBody("upper_percentile_rank", Double.toString(job.getUpperPercentile()));

    // Gene families source
    String orthologsSource = null;
    if (job.getGeneFamiliesSource() == GeneFamiliesSource.PLAZA) {
        orthologsSource = "plaza";
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.CUSTOM) {
        orthologsSource = "custom";
        entityBuilder.addBinaryBody("gene_families", job.getGeneFamiliesPath().toFile(), ContentType.TEXT_PLAIN,
                job.getGeneFamiliesPath().getFileName().toString());
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.NONE) {
        orthologsSource = "none";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("gene_families_source", orthologsSource);

    return entityBuilder.build();
}

From source file:com.collaide.fileuploader.requests.repository.FilesRequest.java

/**
 * send a file on the server/*from w  w  w . j  a v a 2 s .c om*/
 *
 * @param file the file to send
 * @param id the id of the folder (on the server) to send the file. If the
 * id is equal to zero, the file is send to the root repository
 */
public void create(File file, int id) {
    HttpPost httppost = getHttpPostForCreate();
    FileBody bin = new FileBody(file);
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().addPart("repo_file[file]", bin)
            .addTextBody("authenticity_token", CurrentUser.getUser().getCsrf());
    if (id != 0) {
        reqEntity.addTextBody("repo_file[id]", String.valueOf(id));
    }
    httppost.setEntity(reqEntity.build());
    httppost.setHeader("X-CSRF-Token", CurrentUser.getUser().getCsrf());
    SendFileThread sendFile = new SendFileThread(httppost, getHttpClient());
    sendFile.start();
    getSendFileList().add(sendFile);
    if (getSendFileList().size() >= getMaxConnection()) {
        terminate();
    }
}