Java HttpClient – Upload a File to the Server

In this tutorial, we will see how to use the Java HttpClient to upload a file to the server. And in the following tutorial, you will learn how to configure HttpClient to accept all SSL certificates. So let’s begin. 

In the below code example, I we will use the Apache HttpClient and the MultipartEntityBuilder.

First, we need to add the following Maven dependencies:

<!-- -->

<!-- -->

If you are not using Maven, you can also download JAR files from the Maven repository.

Java HttpClient – upload a file to the server

Below is an example of how to upload a file to the server with the HTTP POST request:

import org.apache.http.HttpHeaders;
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.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;


public class Test {

  public static void main(String[] args) {

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

      File file = new File("path_to_file");

      MultipartEntityBuilder builder = MultipartEntityBuilder.create();

      builder.addPart("paramName", new FileBody(file));

      HttpUriRequest request =
              .setHeader(HttpHeaders.ACCEPT, "application/json")
              .setHeader("Authorization", "Bearer 123token")

      HttpResponse response = httpClient.execute(request);

      // Get the http status code
      int statusCode = response.getStatusLine().getStatusCode();

      System.out.println("Status code: " + statusCode);

      // Get the response message
      String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

      System.out.println("Response from server: " + responseBody);
    } catch (Exception e) {
      System.out.println("Uploading file failed...");

That’s it!

Leave a Reply

Your email address will not be published.