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:de.yaio.commons.http.HttpUtils.java

/** 
 * execute POST-Request for url with params
 * @param baseUrl                the url to call
 * @param username               username for auth
 * @param password               password for auth
 * @param params                 params for the request
 * @param textFileParams         text-files to upload
 * @param binFileParams          bin-files to upload
 * @return                       HttpResponse
 * @throws IOException           possible Exception if Request-state <200 > 299 
 *///ww w  .  j a  va2  s.c  o  m
public static HttpResponse callPatchUrlPure(final String baseUrl, final String username, final String password,
        final Map<String, String> params, final Map<String, String> textFileParams,
        final Map<String, String> binFileParams) throws IOException {
    // create request
    HttpPatch request = new HttpPatch(baseUrl);

    // map params
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (MapUtils.isNotEmpty(params)) {
        for (String key : params.keySet()) {
            builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
        }
    }

    // map files
    if (MapUtils.isNotEmpty(textFileParams)) {
        for (String key : textFileParams.keySet()) {
            File file = new File(textFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key));
        }
    }
    // map files
    if (MapUtils.isNotEmpty(binFileParams)) {
        for (String key : binFileParams.keySet()) {
            File file = new File(binFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key));
        }
    }

    // set request
    HttpEntity multipart = builder.build();
    request.setEntity(multipart);

    // add request header
    request.addHeader("User-Agent", "YAIOCaller");

    // call url
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sending 'PATCH' request to URL : " + baseUrl);
    }
    HttpResponse response = executeRequest(request, username, password);

    // get response
    int retCode = response.getStatusLine().getStatusCode();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Response Code : " + retCode);
    }
    return response;
}

From source file:com.movilizer.mds.webservice.models.MovilizerUploadForm.java

/**
 * Create an HTTP multipart form to perform a request.
 *
 * @param file with the document to be uploaded.
 * @param filename of the document./*from   w ww.  j a v a  2s  .c o m*/
 * @param systemId of Movilizer Cloud.
 * @param password for the system id.
 * @param pool to store the document at.
 * @param key to find the document in the pool.
 * @param lang of the document.
 * @param suffix ending of the document (".zip" for HTML5 apps).
 * @param ack value that the cloud will return to you when the document is uploaded.
 * @return HttpEntity to be used in the request.
 */
public HttpEntity getForm(InputStream file, String filename, long systemId, String password, String pool,
        String key, String lang, String suffix, String ack) {
    MultipartEntityBuilder form = getForm(systemId, password, pool, key, lang, suffix, ack);
    form.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, filename);
    return form.build();
}

From source file:com.movilizer.mds.webservice.models.MovilizerUploadForm.java

/**
 * Create an HTTP multipart form to perform a request.
 *
 * @param file with the document to be uploaded.
 * @param systemId of Movilizer Cloud./*from  www.  java2  s  . co  m*/
 * @param password for the system id.
 * @param pool to store the document at.
 * @param key to find the document in the pool.
 * @param lang of the document.
 * @param suffix ending of the document (".zip" for HTML5 apps).
 * @param ack value that the cloud will return to you when the document is uploaded.
 * @return HttpEntity to be used in the request.
 */
public HttpEntity getForm(File file, long systemId, String password, String pool, String key, String lang,
        String suffix, String ack) {
    MultipartEntityBuilder form = getForm(systemId, password, pool, key, lang, suffix, ack);
    form.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
    return form.build();
}

From source file:com.cloudera.livy.client.http.LivyConnection.java

synchronized <V> V post(File f, Class<V> retType, String paramName, String uri, Object... uriParams)
        throws Exception {
    HttpPost post = new HttpPost();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart(paramName, new FileBody(f));
    post.setEntity(builder.build());
    return sendRequest(post, retType, uri, uriParams);
}

From source file:gda.util.ElogEntry.java

/**
 * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php"
 * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the
 * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be
 * either the development or production databases.
 * /* ww  w.ja  v a  2s . c  o  m*/
 * @param title
 *            The ELog title
 * @param content
 *            The ELog content
 * @param userID
 *            The user ID e.g. epics or gda or abc12345
 * @param visit
 *            The visit number
 * @param logID
 *            The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11,
 *            BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall
 *            Coordinators, OM = Optics and Meteorology, OPR = Operations, E
 * @param groupID
 *            The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics
 *            and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line,
 * @param fileLocations
 *            The image file names with path to upload
 * @throws ELogEntryException
 */
public static void post(String title, String content, String userID, String visit, String logID, String groupID,
        String[] fileLocations) throws ELogEntryException {
    String targetURL = POST_UPLOAD_URL;
    try {
        String entryType = "41";// entry type is always a log (41)
        String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title;

        MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost)
                .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID)
                .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType)
                .addTextBody("txtUSERID", userID);

        if (fileLocations != null) {
            for (int i = 1; i < fileLocations.length + 1; i++) {
                File targetFile = new File(fileLocations[i - 1]);
                request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"),
                        targetFile.getName());
            }
        }

        HttpEntity entity = request.build();
        targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL);
        HttpPost httpPost = new HttpPost(targetURL);
        httpPost.setEntity(entity);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
            if (!responseString.contains("New Log Entry ID")) {
                throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode()
                        + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = "
                        + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = "
                        + entryType + " userID = " + userID);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    } catch (ELogEntryException e) {
        throw e;
    } catch (Exception e) {
        throw new ELogEntryException("Error in ELogger.  Database:" + targetURL, e);
    }
}

From source file:com.codota.uploader.Uploader.java

private void uploadFile(File file, String uploadUrl) throws IOException {
    HttpPut putRequest = new HttpPut(uploadUrl);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("code", new FileBody(file));
    final HttpEntity entity = builder.build();
    putRequest.setEntity(entity);/* w w  w .ja  v a2s.  c o  m*/

    putRequest.setHeader("enctype", "multipart/form-data");
    putRequest.setHeader("authorization", "bearer " + token);
    httpClient.execute(putRequest, new UploadResponseHandler());
}

From source file:org.apache.sling.hapi.client.forms.internal.FormValues.java

public HttpEntity toMultipartEntity() {
    MultipartEntityBuilder eb = MultipartEntityBuilder.create();
    for (NameValuePair p : list.flatten()) {
        eb.addTextBody(p.getName(), p.getValue());
    }//from   www  .  jav  a2s.co  m
    return eb.build();
}

From source file:ApkItem.java

public void uploadFile() {
    try {/*from  w  ww  .j  a  v  a2  s. c o m*/
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://192.168.1.130:8080/imooc/");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
        HttpEntity multipart = builder.build();
        CountingMultipartRequestEntity.ProgressListener pListener = new CountingMultipartRequestEntity.ProgressListener() {
            @Override
            public void progress(float percentage) {
                apkState.setProcess((int) percentage);
                firePropertyChange("uploadProcess", -1, percentage);
            }
        };
        httpPost.setEntity(new CountingMultipartRequestEntity.ProgressEntityWrapper(multipart, pListener));
        CloseableHttpResponse response = client.execute(httpPost);
        client.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.mule.service.http.impl.functional.server.HttpServerPartsTestCase.java

private HttpEntity getMultipartEntity() {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody(TEXT_BODY_FIELD_NAME, TEXT_BODY_FIELD_VALUE, TEXT_PLAIN);
    return builder.build();
}

From source file:org.apache.heron.uploader.http.HttpUploader.java

private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
        throws IOException, URISyntaxException {
    File file = new File(this.topologyPackageLocation);
    String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
    post = new HttpPost(uploaderUri);
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart(FILE, fileBody);//w  w  w  . jav  a  2 s.c  om
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    HttpResponse response = execute(httpclient);
    String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name());
    LOG.fine("Topology package download URI: " + responseString);

    return new URI(responseString);
}