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:
<!-- 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 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; 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..."); } } }
That’s it!