How to upload file using Apache HttpClient in Java?

This entry is part 6 of 6 in the series Apache HttpClient Tutorial

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...!!! Click To Tweet

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

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


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:


Let’s try to understand the code:

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


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


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


4. Submit the Request using HttpPost -> Execute method


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


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


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


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


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...!!! Click To Tweet


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

Other Useful References:


Related Posts:

[wcp-carousel id=”5342″]
Series Navigation<< Basic Authentication using Apache HttpClient

Leave a Reply

Your email address will not be published.Required fields are marked *

Facebook Twitter Instagram YouTube