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?”
Simple representation of upload a file using Apache HttpClient in Java...!!! Share on XHere 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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
1 2 3 4 5 | 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
1 2 3 | HttpEntity postData = MultipartEntityBuilder.create() .addBinaryBody("upfile", testUploadFile) .build(); |
3. Build HttpUriRequest object and assign HttpEntity object to it that we build above
1 2 3 | HttpUriRequest postRequest = RequestBuilder .post(postEndpoint) .setEntity(postData) .build(); |
4. Submit the Request using HttpPost -> Execute method
1 | HttpResponse response = httpclient.execute(postRequest); |
5. Create a BufferedReader object and store the raw Response content into it.
1 | BufferedReader br = new BufferedReader( new InputStreamReader((response.<wbr />getEntity().getContent()))); |
6. Throw runtime exception if status code isn’t 200
1 2 3 | if (response.getStatusLine().<wbr />getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().<wbr />getStatusCode()); } |
7. Create the StringBuffer object and store the response into it.
1 2 3 4 5 6 7 | StringBuffer result = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { result.append(line); } |
Let’s have a look at the Eclipse Console Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | [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 XIf you like this post , please check out my other useful blog posts:
Other Useful References: