Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

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

Prototype

public MultipartEntity(final HttpMultipartMode mode) 

Source Link

Usage

From source file:cn.dacas.emmclient.security.ssl.SslHttpStack.java

/**
 * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
 * @param httpRequest/*from   w w w . j  a  v a  2s .  c o  m*/
 * @param request
 * @throws AuthFailureError
 */
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {

    // Return if Request is not MultiPartRequest
    if (request instanceof MultiPartRequest == false) {
        return;
    }

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    //Iterate the fileUploads
    Map<String, File> fileUpload = ((MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        multipartEntity.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }

    //Iterate the stringUploads
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        try {
            multipartEntity.addPart(((String) entry.getKey()), new StringBody((String) entry.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    httpRequest.setEntity(multipartEntity);
}

From source file:com.ring.ytjojo.ssl.SslHttpStack.java

/**
 * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
 * @param httpRequest//from ww w .j  a  v a  2s  .c o m
 * @param request
 * @throws AuthFailureError
 */
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {

    // Return if Request is not MultiPartRequest
    if (request instanceof MultiPartRequest == false) {
        return;
    }

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    //Iterate the fileUploads
    Map<String, File> fileUpload = ((com.ring.ytjojo.volley.MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        multipartEntity.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }

    //Iterate the stringUploads
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        try {
            multipartEntity.addPart(((String) entry.getKey()), new StringBody((String) entry.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    httpRequest.setEntity(multipartEntity);
}

From source file:org.r10r.doctester.testbrowser.TestBrowserImpl.java

private Response makePatchPostOrPutRequest(Request httpRequest) {

    org.apache.http.HttpResponse apacheHttpClientResponse;
    Response response = null;//w w w .ja va  2 s  .com

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpEntityEnclosingRequestBase apacheHttpRequest;

        if (PATCH.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPatch(httpRequest.uri);

        } else if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPost(httpRequest.uri);

        } else {

            apacheHttpRequest = new HttpPut(httpRequest.uri);
        }

        if (httpRequest.headers != null) {
            // add all headers
            for (Entry<String, String> header : httpRequest.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        ///////////////////////////////////////////////////////////////////
        // Either add form parameters...
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.formParameters != null) {

            List<BasicNameValuePair> formparams = Lists.newArrayList();
            for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) {

                formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
            }

            // encode form parameters and add
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add multipart file upload
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.filesToUpload != null) {

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) {

                // For File parameters
                entity.addPart(entry.getKey(), new FileBody((File) entry.getValue()));

            }

            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add payload and convert if Json or Xml
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.payload != null) {

            if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) {

                String string = new ObjectMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType("application/json; charset=utf-8");

                apacheHttpRequest.setEntity(entity);

            } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) {

                String string = new XmlMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8);

                apacheHttpRequest.setEntity(new StringEntity(string, "utf-8"));

            } else if (httpRequest.payload instanceof String) {

                StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8");
                apacheHttpRequest.setEntity(entity);

            } else {

                StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8");
                apacheHttpRequest.setEntity(entity);

            }

        }

        setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects);

        // Here we go!
        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);
        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        apacheHttpRequest.releaseConnection();

    } catch (IOException e) {
        logger.error("Fatal problem creating PATCH, POST or PUT request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;

}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

public void executeMultipartPost() throws Exception {

    try {/*from ww w  .  j  av  a2  s .co  m*/

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost("http://192.168.14.102/index.php/photos/upload");

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

        Session.image.compress(Bitmap.CompressFormat.PNG, 100, byteStream);

        byte[] buffer = byteStream.toByteArray();

        ByteArrayBody body = new ByteArrayBody(buffer, "profile_image");

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("gambar", body);
        entity.addPart("nama", new StringBody(Session.name)); //POST nama
        entity.addPart("keterangan", new StringBody(Session.caption)); //POST keterangan
        entity.addPart("lat", new StringBody(lat)); //POST keterangan
        entity.addPart("lon", new StringBody(longt)); //POST keterangan
        post.setEntity(entity);

        System.out.println("post entity length " + entity.getContentLength());
        ResponseHandler handler = new BasicResponseHandler();

        String response = client.execute(post, handler);

    } catch (Exception e) {

        Log.e(e.getClass().getName(), e.getMessage());

    }

}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequestToLarge() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/* w  w  w  .j  av  a2 s .  c o m*/
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/2";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(DefaultServer.isH2() || DefaultServer.isAjp() ? StatusCodes.SERVICE_UNAVAILABLE
                : StatusCodes.INTERNAL_SERVER_ERROR, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
    } catch (IOException expected) {
        //in some environments the forced close of the read side will cause a connection reset
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.cloudapp.rest.CloudApi.java

/**
 * Upload a file to the CloudApp servers.
 * /*  ww  w .  j a  va2s.c  o  m*/
 * @param input
 *          The inputstream that holds the content that should be stored on the server.
 * @param filename
 *          The name of this file. i.e.: README.txt
 * @return A JSONObject with the returned output from the CloudApp servers.
 * @throws CloudApiException
 */
@SuppressWarnings("rawtypes")
public JSONObject uploadFile(CloudAppInputStream stream) throws CloudApiException {
    HttpGet keyRequest = null;
    HttpPost uploadRequest = null;
    try {
        // Get a key for the file first.
        keyRequest = new HttpGet("http://my.cl.ly/items/new");
        keyRequest.addHeader("Accept", "application/json");

        // Execute the request.
        HttpResponse response = client.execute(keyRequest);
        int status = response.getStatusLine().getStatusCode();
        if (status == 200) {
            String body = EntityUtils.toString(response.getEntity());
            JSONObject json = new JSONObject(body);
            String url = json.getString("url");
            JSONObject params = json.getJSONObject("params");
            // From the API docs
            // Use this response to construct the upload. Each item in params becomes a
            // separate parameter you'll need to post to url. Send the file as the parameter
            // file.
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            // Add all the plain parameters.
            Iterator keys = params.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                entity.addPart(key, new StringBody(params.getString(key)));
            }

            // Add the actual file.
            // We have to use the 'file' parameter for the S3 storage.
            entity.addPart("file", stream);

            uploadRequest = new HttpPost(url);
            uploadRequest.addHeader("Accept", "application/json");
            uploadRequest.setEntity(entity);

            // Perform the actual upload.
            // uploadMethod.setFollowRedirects(true);
            response = client.execute(uploadRequest);
            status = response.getStatusLine().getStatusCode();
            body = EntityUtils.toString(response.getEntity());
            if (status == 200) {
                return new JSONObject(body);
            }
            throw new CloudApiException(status, "Was unable to upload the file to amazon:\n" + body, null);

        }
        throw new CloudApiException(500, "Was unable to retrieve a key from CloudApp to upload a file.", null);

    } catch (IOException e) {
        LOGGER.error("Error when trying to upload a file.", e);
        throw new CloudApiException(500, e.getMessage(), e);
    } catch (JSONException e) {
        LOGGER.error("Error when trying to convert the return output to JSON.", e);
        throw new CloudApiException(500, e.getMessage(), e);
    } finally {
        if (keyRequest != null) {
            keyRequest.abort();
        }
        if (uploadRequest != null) {
            uploadRequest.abort();
        }
    }
}

From source file:org.doctester.testbrowser.TestBrowserImpl.java

private Response makePostOrPutRequest(Request httpRequest) {

    org.apache.http.HttpResponse apacheHttpClientResponse;
    Response response = null;/*www.jav a2s .co m*/

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpEntityEnclosingRequestBase apacheHttpRequest;

        if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPost(httpRequest.uri);

        } else {

            apacheHttpRequest = new HttpPut(httpRequest.uri);
        }

        if (httpRequest.headers != null) {
            // add all headers
            for (Entry<String, String> header : httpRequest.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        ///////////////////////////////////////////////////////////////////
        // Either add form parameters...
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.formParameters != null) {

            List<BasicNameValuePair> formparams = Lists.newArrayList();
            for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) {

                formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
            }

            // encode form parameters and add
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add multipart file upload
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.filesToUpload != null) {

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) {

                // For File parameters
                entity.addPart(entry.getKey(), new FileBody((File) entry.getValue()));

            }

            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add payload and convert if Json or Xml
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.payload != null) {

            if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) {

                String string = new ObjectMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType("application/json; charset=utf-8");

                apacheHttpRequest.setEntity(entity);

            } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) {

                String string = new XmlMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8);

                apacheHttpRequest.setEntity(new StringEntity(string, "utf-8"));

            } else if (httpRequest.payload instanceof String) {

                StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8");
                apacheHttpRequest.setEntity(entity);

            } else {

                StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8");
                apacheHttpRequest.setEntity(entity);

            }

        }

        setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects);

        // Here we go!
        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);
        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        apacheHttpRequest.releaseConnection();

    } catch (IOException e) {
        logger.error("Fatal problem creating POST or PUT request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;

}

From source file:com.android.volley.toolbox.http.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws IOException, AuthFailureError {

    if (request.containsFile()) {
        /* MultipartEntity multipartEntity = new MultipartEntity();
        final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
        for (String key : multipartParams.keySet()) {
        multipartEntity.addPart(new StringPart(key, multipartParams.get(key).value));
        }/*from  w w  w. j  a va  2s  . c o m*/
                
        final Map<String, File> filesToUpload = request.getFilesToUpload();
        if(filesToUpload!=null){
        for (String key : filesToUpload.keySet()) {
        File file = filesToUpload.get(key) ;
                
        if (file==null || !file.exists()) {
         throw new IOException(String.format("File not found: %s",file.getAbsolutePath()));
        }
                
        if (file.isDirectory()) {
         throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
        }
                
        multipartEntity.addPart(new FilePart(key, file, null, null));
        }
        }
        httpRequest.setEntity(multipartEntity);
        */
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
        for (String key : multipartParams.keySet()) {
            multipartEntity.addPart(key,
                    new StringBody(multipartParams.get(key).value, "text/plain", Charset.forName("UTF-8")));
        }

        final Map<String, File> filesToUpload = request.getFilesToUpload();
        if (filesToUpload != null) {
            for (String key : filesToUpload.keySet()) {
                File file = filesToUpload.get(key);

                if (file == null || !file.exists()) {
                    throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
                }

                if (file.isDirectory()) {
                    throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
                }
                multipartEntity.addPart(key, new FileBody(file));
            }
        }
        httpRequest.setEntity(multipartEntity);

    } else {
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }
}

From source file:info.ajaxplorer.client.http.RestRequest.java

private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName,
        AjxpFileBody fileBody) throws Exception {
    URI originalUri = new URI(uri.toString());
    if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) {
        uri = new URI(
                uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN()));
    }//w w  w  . j  av  a2s .  com
    //Log.d("RestRequest", "Issuing request : " + uri.toString());
    HttpResponse response = null;
    try {
        HttpRequestBase request;

        if (postParameters != null || file != null) {
            request = new HttpPost();
            if (file != null) {

                if (fileBody == null) {
                    if (fileName == null)
                        fileName = file.getName();
                    fileBody = new AjxpFileBody(file, fileName);
                    ProgressListener origPL = this.uploadListener;
                    Map<String, String> caps = RestStateHolder.getInstance().getServer()
                            .getRemoteCapacities(this);
                    this.uploadListener = origPL;
                    int maxUpload = 0;
                    if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT))
                        maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT));
                    maxUpload = Math.min(maxUpload, 60000000);
                    if (maxUpload > 0 && maxUpload < file.length()) {
                        fileBody.chunkIntoPieces(maxUpload);
                        if (uploadListener != null) {
                            uploadListener.partTransferred(fileBody.getCurrentIndex(),
                                    fileBody.getTotalChunks());
                        }
                    }
                } else {
                    if (uploadListener != null) {
                        uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks());
                    }
                }
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("userfile_0", fileBody);

                if (fileName != null && !EncodingUtils
                        .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) {
                    reqEntity.addPart("urlencoded_filename",
                            new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8")));
                }
                if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) {
                    reqEntity.addPart("appendto_urlencoded_part",
                            new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8")));
                }
                if (postParameters != null) {
                    Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> entry = it.next();
                        reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
                    }
                }
                if (uploadListener != null) {
                    CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity(
                            reqEntity, uploadListener);
                    ((HttpPost) request).setEntity(countingEntity);
                } else {
                    ((HttpPost) request).setEntity(reqEntity);
                }
            } else {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
                Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } else {
            request = new HttpGet();
        }

        request.setURI(uri);
        if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) {
            request.addHeader("Ajxp-Force-Login", "true");
        }
        response = httpClient.executeInContext(request);
        if (isAuthenticationRequested(response)) {
            sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH);
            this.discardResponse(response);
            this.authenticate();
            if (loginStateChanged) {
                // RELOAD
                loginStateChanged = false;
                sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA);
                if (fileBody != null)
                    fileBody.resetChunkIndex();
                return this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
            }
        } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) {
            this.discardResponse(response);
            this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
        }
    } catch (ClientProtocolException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (AuthenticationException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        throw e;
    } catch (Exception e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } finally {
        uploadListener = null;
    }
    return response;
}

From source file:com.gistlabs.mechanize.requestor.RequestBuilder.java

private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters,
        final Map<String, ContentBody> files) {
    HttpPost request = new HttpPost(uri);
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {/*from  w ww .  j a  v a2s .  c o m*/
        Charset utf8 = Charset.forName("UTF-8");
        for (Parameter param : parameters)
            if (param.isSingleValue())
                multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8));
            else
                for (String value : param.getValues())
                    multiPartEntity.addPart(param.getName(), new StringBody(value, utf8));
    } catch (UnsupportedEncodingException e) {
        throw MechanizeExceptionFactory.newException(e);
    }

    List<String> fileNames = new ArrayList<String>(files.keySet());
    Collections.sort(fileNames);
    for (String name : fileNames) {
        ContentBody contentBody = files.get(name);
        multiPartEntity.addPart(name, contentBody);
    }
    request.setEntity(multiPartEntity);
    return request;
}