Tuesday, August 18, 2015

How to make a POST request in Java with multipart-form encoding with parameters and a file upload



download httpcore-4.4.1.jar, httpclient-4.5.jar and httpmime-4.5.jar from this link
http://ftp.wayne.edu/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5-bin.zip

extract zip file, go into lib directory, get jars and add to your projects WEB-INF/lib folder
Then add jars to build classpath in eclipse


In your java code, paste this code and resolve dependencies, then run it.

resumeFile is a File
urlString is the full URL of the rest API you're connecting to
paramName1/value1 should be self explanatory
cookieValue is used in some API's if there is authentication via cookies

====================

        CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(urlString);
   
        // This is how to set a header cookie if you need one
    httpPost.addHeader("Cookie",  "cookieValue");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("paramName1", "paramValue1", ContentType.TEXT_PLAIN);
     builder.addTextBody("paramName2", "paramValue2", ContentType.TEXT_PLAIN);
     builder.addTextBody("paramName3", "paramValue3", ContentType.TEXT_PLAIN);
   
    builder.addBinaryBody("ResumeFile", resumeFile);
   
    HttpEntity multipart = builder.build();

    httpPost.setEntity(multipart);

        try
        {
                
        CloseableHttpResponse response = httpClient.execute(httpPost);
       
        if(response.getStatusLine().getStatusCode() == 200 )
        {
HttpEntity entity = response.getEntity();
if (entity != null)
{
String responseBody = EntityUtils.toString(entity);
System.out.println("finalResult: " + responseBody.toString());
                } else {
                log.info("Entity is null");
                }        
        }
     
        } catch (IOException e) {
            e.printStackTrace();
        }