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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:com.nc.common.utils.HttpUtils.java

/**
 * <pre>/*from   ww  w. j a v a2 s . c o  m*/
 * 1.  : http  
 * 2.  : OpenAPI Multipart 
 * </pre>
 *
 * @method Name : execOpenAPIMultipart
 * @param String subUrl, Map<String, Object> paramMap
 * @return String
 * @throws Exception
 * 
 */
public String execOpenAPIMultipart(String subUrl, Map<String, Object> paramMap) throws Exception {
    String result = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        HttpPost httpPost = new HttpPost(new URI(serverOpenAPI + subUrl));
        // httpPost.addHeader("Content-Type", "application/json");

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .setCharset(Charset.forName(CommonConstants.DEFAULT_CHARSET));

        Iterator<String> iter = paramMap.keySet().iterator();
        String key = null;
        String val = null;

        while (iter.hasNext()) {
            key = iter.next();
            val = (String) paramMap.get(key);

            if (log.isDebugEnabled()) {
                log.debug(
                        "==========================================================================================");
                log.debug(" = ? : [{} - {}] =", key, val);
                log.debug(
                        "==========================================================================================");
            }

            multipartEntityBuilder.addTextBody(key, val);
        }
        httpPost.setEntity(multipartEntityBuilder.build());

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API   : [{}]", httpPost);
            log.debug(
                    "==========================================================================================");
        }

        CloseableHttpResponse response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API  ? : [{}]", statusLine);
            log.debug(
                    "==========================================================================================");
        }

        try {
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, CommonConstants.DEFAULT_CHARSET);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "==========================================================================================");
                        log.debug("= API    : [{}] =", result);
                        log.debug(
                                "==========================================================================================");
                    }
                }
                EntityUtils.consume(entity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

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:com.oltpbenchmark.util.ResultUploader.java

public void uploadResult(List<TransactionType> activeTXTypes) throws ParseException {
    try {/*from  www.j a  v  a 2  s . c  om*/
        File expConfigFile = File.createTempFile("expconfig", ".tmp");
        File samplesFile = File.createTempFile("samples", ".tmp");
        File summaryFile = File.createTempFile("summary", ".tmp");
        File paramsFile = File.createTempFile("params", ".tmp");
        File metricsFile = File.createTempFile("metrics", ".tmp");
        File csvDataFile = File.createTempFile("csv", ".gz");

        PrintStream confOut = new PrintStream(new FileOutputStream(expConfigFile));
        writeBenchmarkConf(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(paramsFile));
        writeDBParameters(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(metricsFile));
        writeDBMetrics(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(samplesFile));
        results.writeCSV2(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(summaryFile));
        writeSummary(confOut);
        confOut.close();

        confOut = new PrintStream(new GZIPOutputStream(new FileOutputStream(csvDataFile)));
        results.writeAllCSVAbsoluteTiming(activeTXTypes, confOut);
        confOut.close();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(uploadUrl);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addTextBody("upload_code", uploadCode)
                .addPart("sample_data", new FileBody(samplesFile))
                .addPart("raw_data", new FileBody(csvDataFile))
                .addPart("db_parameters_data", new FileBody(paramsFile))
                .addPart("db_metrics_data", new FileBody(metricsFile))
                .addPart("benchmark_conf_data", new FileBody(expConfigFile))
                .addPart("summary_data", new FileBody(summaryFile)).build();

        httppost.setEntity(reqEntity);

        LOG.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity resEntity = response.getEntity();
            LOG.info(IOUtils.toString(resEntity.getContent()));
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (ConfigurationException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

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

/**
 * Uploads a file to the server./* w w  w.  j a v a 2 s .c o  m*/
 * @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:MainFrame.HttpCommunicator.java

public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException {
    String response = null;/*from  ww w.  j av a2s.  c o  m*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.removeLesson", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    }

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:org.phenotips.integration.medsavant.internal.JsonMedSavantServer.java

@Override
public boolean uploadVCF(Patient patient) {
    HttpPost method = null;//from   w ww  .java  2s  .com
    try {
        MultipartEntityBuilder data = MultipartEntityBuilder.create();
        PatientData<String> identifiers = patient.getData("identifiers");
        String url = getMethodURL("UploadManager", "upload");
        String eid = identifiers.get("external_id");
        XWikiContext context = Utils.getContext();
        XWikiDocument doc = context.getWiki().getDocument(patient.getDocument(), context);
        method = new HttpPost(url);

        boolean hasData = false;
        for (XWikiAttachment attachment : doc.getAttachmentList()) {
            if (StringUtils.endsWithIgnoreCase(attachment.getFilename(), ".vcf")
                    && isCorrectVCF(attachment, eid, context)) {
                data.addBinaryBody(patient.getId() + ".vcf", attachment.getContentInputStream(context));
                hasData = true;
            }
        }
        if (hasData) {
            method.setEntity(data.build());
            this.client.execute(method).close();
            return true;
        }
    } catch (Exception ex) {
        this.logger.warn("Failed to upload VCF for patient [{}]: {}", patient.getDocument(), ex.getMessage(),
                ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return false;
}

From source file:org.piwigo.remotesync.api.client.WSClient.java

@SuppressWarnings("unchecked")
protected <T extends BasicResponse> CloseableHttpResponse getHttpResponse(AbstractRequest<T> request)
        throws ClientException {
    try {/*from w w  w.j  a  v a2  s  .  c o  m*/
        HttpPost method = new HttpPost(clientConfiguration.getUrl() + "/ws.php");
        method.setConfig(requestConfig);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addTextBody("method", request.getWSMethodName());
        for (Entry<String, Object> entry : request.getParameters().entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof File)
                multipartEntityBuilder.addBinaryBody(key, (File) value);
            else if (value == null)
                multipartEntityBuilder.addTextBody(key, "");
            else if (value instanceof List) {
                for (Object object : (List<? extends Object>) value)
                    if (object != null)
                        multipartEntityBuilder.addTextBody(key + "[]", object.toString());
            } else if (value instanceof Enum)
                multipartEntityBuilder.addTextBody(key, value.toString().toLowerCase());
            else
                multipartEntityBuilder.addTextBody(key, value.toString());
        }
        method.setEntity(multipartEntityBuilder.build());

        return getHttpClient().execute(method);
    } catch (SSLException e) {
        throw new ClientSSLException("SSL certificate exception (Please try option 'Trust SSL certificates')",
                e);
    } catch (Exception e) {
        throw new ClientException("Unable to send request", e);
    }
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?MultipartHttp??????ContentBody map//w ww  .j  a  v  a  2  s  .c  o m
 */
public static String fetchMultipartHttpResponse(String contentUrl, Map<String, String> headerMap,
        Map<String, ContentBody> bodyMap) throws IOException {
    try {
        HttpPost httpPost = new HttpPost(contentUrl);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                httpPost.addHeader(m.getKey(), m.getValue());
            }
        }
        if (bodyMap != null && !bodyMap.isEmpty()) {
            for (Map.Entry<String, ContentBody> m : bodyMap.entrySet()) {
                multipartEntityBuilder.addPart(m.getKey(), m.getValue());
            }
        }
        HttpEntity reqEntity = multipartEntityBuilder.build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity resEntity = response.getEntity();
            String resStr = IOUtils.toString(resEntity.getContent());
            return resStr;
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            response.close();
        }

    } finally {
        httpClient.close();
    }
    return null;

}

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

/**
 * @param postRequest//ww w. ja  v a  2s .  c  o m
 * @param postParams
 * @return
 * @throws java.io.IOException
 */
public Response doPostRequest(String uploadHost, String postRequest, String postParams, InputStream stream,
        String mimeType, String filename) throws IOException {
    HttpPost httpPost = new HttpPost(uploadHost + postRequest);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addBinaryBody("file", stream, ContentType.create(mimeType), filename);

    List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8"));
    for (NameValuePair nameValuePair : nvps) {
        mpBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
    }
    httpPost.setEntity(mpBuilder.build());

    return UnmarshallUtil.unmarshall(getXmlTransformedResponse(httpPost));
}