Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

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

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

public static String doPost(String requestUrl, Map<String, String> paramsMap, Map<String, InputStream> files)
        throws Exception {

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(500)
            .setSocketTimeout(20000).setConnectTimeout(20000).build();

    // ?/*from  w  ww  .j  a v a2 s  .  c  o m*/
    MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName(charset));

    if (paramsMap != null) {
        Set<Entry<String, String>> paramsSet = paramsMap.entrySet();
        for (Entry<String, String> entry : paramsSet) {
            mbuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", charset));
        }
    }

    if (files != null) {
        Set<Entry<String, InputStream>> filesSet = files.entrySet();
        for (Entry<String, InputStream> entry : filesSet) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            InputStream is = entry.getValue();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.close();
            is.close();
            mbuilder.addBinaryBody("attachment", os.toByteArray(), ContentType.APPLICATION_OCTET_STREAM,
                    entry.getKey());
        }
    }

    HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setConfig(requestConfig);

    HttpEntity httpEntity = mbuilder.build();

    httpPost.setEntity(httpEntity);

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };

    return httpClient.execute(httpPost, responseHandler);
}