There could be a service which takes a file as an input and upload it to the server or cloud storage etc. It could be any kind of file like text data, image etc. Lets take this simple scenario, you’ve might be using some social media applications like facebook, instagram etc. And, you might uploaded your images on those applications. Let’s assume there is a service behind it which handles the image upload.  Apache HttpClient has the capability to test that. In this example, we are going to see How to upload a multi-part file and send it with the HTTP POST request using HttpClient?”

Upload_Multi_Part_File_HttpClient_Techndeck

Simple representation of upload a file using Apache HttpClient in Java...!!! Share on X

Here are some details about the service that we are going to test by uploading the file:

  • Endpoint : http://httpbin.org/post
  • Request Type : POST
  • File to upload : any file (here we are uploading ‘.png’ format image file)

Objective:

At the above service endpoint URL, we are going to Upload a file and validate it’s response.

Here is the code to upload a multipart file using HttpClient through the POST request:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.testng.annotations.Test;
public class HttpClient_MultiPart_File_Upload {

    @Test
    public void uploadFile() throws IOException {

        String postEndpoint = "http://httpbin.org/post";

        File testUploadFile = new File("C:\\temp\\testfile.png"); //Specify your own location and file 

        CloseableHttpClient httpclient = HttpClients.createDefault();

        // build httpentity object and assign the file that need to be uploaded 
        HttpEntity postData = MultipartEntityBuilder.create().addBinaryBody("upfile", testUploadFile).build();

        // build http request and assign httpentity object to it that we build above 
        HttpUriRequest postRequest = RequestBuilder.post(postEndpoint).setEntity(postData).build();

        System.out.println("Executing request " + postRequest.getRequestLine());

        HttpResponse response = httpclient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        //Throw runtime exception if status code isn't 200 
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        //Create the StringBuffer object and store the response into it. 
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            result.append(line);
        }

        System.out.println("Response : \n" + result);
    }
}

Let’s try to understand the code:

1. Specify the Endpoint URL, File to Upload and set up CloseableHttpClient object

String postEndpoint = "http://dummy.restapiexample.com/api/v1/create"; 

File testUploadFile = new File("C:\\temp\\testfile.png");

CloseableHttpClient httpclient = HttpClients.createDefault();

2. Build HttpEntity object and assign the file that need to be uploaded

HttpEntity postData = MultipartEntityBuilder.create() 
                      .addBinaryBody("upfile", testUploadFile) 
                      .build();

3. Build HttpUriRequest object and assign HttpEntity object to it that we build above

HttpUriRequest postRequest = RequestBuilder .post(postEndpoint) 
                                            .setEntity(postData) 
                                            .build();

4. Submit the Request using HttpPost -> Execute method

HttpResponse response = httpclient.execute(postRequest);

5. Create a BufferedReader object and store the raw Response content into it.

BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent())));

6. Throw runtime exception if status code isn’t 200

if (response.getStatusLine().getStatusCode() != 200) { 
       throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); 
    }

7. Create the StringBuffer object and store the response into it.

StringBuffer result = new StringBuffer(); 

String line = ""; 

while ((line = br.readLine()) != null) { 
         result.append(line); 
      }

Let’s have a look at the Eclipse Console Output:

[RemoteTestNG] detected TestNG version 6.14.3
Executing request POST http://httpbin.org/post HTTP/1.1
Response : 
{  
   "args":{  

   },
   "data":"",
   "files":{  
      "upfile":"data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABfElEQVR42rXRy0pCURiG4X0LVnYNDWoaEd1DEDRo2qRRUImIlWVhmEkRZE1CtOykpGZYinYGM4omIphBloe0rJ2ZbnWr9YWBgrUsJy14YMEP779gUdR/HOdOP6pFDLDZPKrxZ+D41FtRYe4w88iB60MZ/JdrSLP5X51s88mBfUk9HIpmuIy9SKYypa1MJl92P9gSgLKJuXO2Me7tN2CTAZxrOnGmakeMfkQilfvBbhCCsozWv9M+czgZOQ0WJaIX+GADeE/74LGP42i2BQ9BDxq6F0riTA7WzSFQ5sE6fDDuX7l3B2GbbIJQrseA1IQekRaxZBZm3Qgok6AWjEeC3N0M0ZWVD+tEI/zei7IX0G9ZmDbEoPQ8jlHPq8F36ZspONVdsMpaEQr58RTP/mBYHSf/gq6PA4usDXuKDoSjL9BaXF8eX9myu04jIQeMw01waEUI0wwiMbai9SUpOXBPZ1BQ3EZSmK+oZORA8DmDaqiVcnJAszyfqIZycRqfnidnf2yv3DYAAAAASUVORK5CYII="
   },
   "form":{  

   },
   "headers":{  
      "Accept-Encoding":"gzip,deflate",
      "Content-Length":"658",
      "Content-Type":"multipart/form-data; boundary=Os1Z5hKI6hUIbQuus3e9juHKbXLqlb",
      "Host":"httpbin.org",
      "User-Agent":"Apache-HttpClient/4.5.9 (Java/1.8.0_201)"
   },
   "json":null,
   "origin":"73.125.64.196, 73.125.64.196",
   "url":"https://httpbin.org/post"
}
PASSED: uploadFile

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

That’s it, it’s that simple to upload a file using Apache HttpClient in Java: ?

Simple representation of upload a file using Apache HttpClient in Java...!!! Share on X

If you like this post , please check out my other useful blog posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts