Java File Upload using HttpClient

In this tutorial, we will explore how to use the Java HttpClient to upload a file to the server. In the next tutorial, we will cover how to configure HttpClient to accept all SSL certificates. Let’s get started!

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

HttpClient Maven Dependencies

First, we need to add the following Maven dependencies:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.13</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.3.1</version>
</dependency>

If you are not using Maven, you can refer to this tutorial Create Java Project with Maven in order to get started.

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;

import java.io.File;

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 = RequestBuilder.post()
                    .setUri("url")
                    .setHeader(HttpHeaders.ACCEPT, "application/json")
                    .setHeader("Authorization", "Bearer 123token")
                    .setEntity(builder.build()).build();
            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...");
        }
    }
}

Here is a high-level overview of the code and what each section does:

  • We import the necessary libraries that will be used in our code. These libraries include org.apache.http.* and java.io.* (Lines  1-11)
  • We define our main class, Test, which will contain the logic for uploading a file to a server (Line 13)
  • We create a CloseableHttpClient instance using the HttpClients.createDefault() method. This is done to create an HTTP client that can be used to communicate with the server (Line 15)
  • We create a File object that represents the file we want to upload to the server (Line 16)
  • We create a MultipartEntityBuilder instance using the MultipartEntityBuilder.create() method. This is used to build a multipart HTTP request that can be used to send the file to the server (Line 17)
  • We add a FileBody object to the MultipartEntityBuilder using the builder.addPart() method. The FileBody object represents the file that we want to upload and the paramName is the name that the file will be given on the server (Line 18)
  • We create an HttpUriRequest object using the RequestBuilder.post() method. This specifies that we want to make a POST request to the server. We also set the URI of the request, and add two headers to the request, ACCEPT and Authorization (Lines 19-23)
  • We execute the HTTP request using the httpClient.execute() method, which sends the request to the server and returns a HttpResponse object (Line 24)
  • We get the HTTP status code from the HttpResponse object using the response.getStatusLine().getStatusCode() method. This will give us the HTTP status code returned by the server (Lines 27-28)
  • We get the response message from the HttpResponse object using the response.getEntity() method. We then convert the response message to a String using the EntityUtils.toString() method and print it to the console (Lines 31-32)
  • If any exceptions are thrown during the execution of the code, we catch them and print a message to the console indicating that the file upload failed (Lines 33-34)

 

Leave a Reply

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