Apache HttpClient PUT HTTP Request Example

Introduction

Apache HttpClient is a robust and flexible library for handling HTTP requests in Java. It supports various HTTP methods, including GET, POST, PUT, DELETE, and more. In this tutorial, we will focus on making a PUT HTTP request using Apache HttpClient. PUT requests are typically used to update an existing resource on the server. We will demonstrate how to send a PUT request with JSON data and handle the response.

Maven Dependencies

To use Apache HttpClient, you need to add the following dependency to your pom.xml file:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>

Example Scenario

We will create a simple Java class that sends a PUT request to a specified URL with JSON data and prints the response.

JSONPlaceholder API

We will use the JSONPlaceholder API for this example. The JSONPlaceholder API provides fake online RESTful endpoints for testing and prototyping. The URL for the PUT endpoint is:

https://jsonplaceholder.typicode.com/posts/1

Java Class for Sending PUT Request

Create a class named HttpClientPutExample with the following code:

import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientPutExample {

    public static void main(String[] args) {
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        String json = "{\"id\":1,\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

        // Create HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            
            // Create HttpPut request
            HttpPut request = new HttpPut(url);
            
            // Set JSON payload
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            request.setEntity(entity);
            
            // Set headers
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");
            
            // Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                
                // Get HttpResponse Status
                System.out.println("Response Code: " + response.getCode());
                
                // Get HttpResponse Content
                String content = EntityUtils.toString(response.getEntity());
                System.out.println("Response Content: \n" + content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation

  1. Adding Maven Dependencies:

    • The org.apache.httpcomponents.client5:httpclient5 dependency provides the classes needed to create and execute HTTP requests using Apache HttpClient.
  2. Creating HttpClient:

    • CloseableHttpClient httpClient = HttpClients.createDefault(); creates an instance of CloseableHttpClient using the default configuration.
  3. Creating HttpPut Request:

    • HttpPut request = new HttpPut(url); creates an HttpPut request for the specified URL.
  4. Setting JSON Payload:

    • StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); creates a StringEntity with the JSON data and sets the content type to application/json.
    • request.setEntity(entity); sets the entity (payload) for the PUT request.
  5. Setting Headers:

    • request.setHeader("Accept", "application/json"); sets the Accept header to application/json.
    • request.setHeader("Content-type", "application/json"); sets the Content-type header to application/json.
  6. Executing the Request:

    • try (CloseableHttpResponse response = httpClient.execute(request)) { ... } executes the PUT request and retrieves the response.
  7. Getting HttpResponse Status:

    • System.out.println("Response Code: " + response.getCode()); prints the status code of the HTTP response.
  8. Getting HttpResponse Content:

    • String content = EntityUtils.toString(response.getEntity()); converts the response entity to a string and prints the content.

Running the Example

To run the example, simply execute the HttpClientPutExample class. You should see the status code and the content of the response printed in the console.

Example Output

Response Code: 200
Response Content: 
{
  "id": 1,
  "title": "foo",
  "body": "bar",
  "userId": 1
}

Additional Configuration

Setting Custom Headers

You can set custom headers for the PUT request by using the setHeader method on the HttpPut object.

request.setHeader("User-Agent", "Mozilla/5.0");

Handling Redirects

By default, Apache HttpClient handles redirects automatically. You can customize this behavior by using a custom HttpClientBuilder.

CloseableHttpClient httpClient = HttpClients.custom()
    .setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return true;
        }
    })
    .build();

Setting Timeouts

You can set connection and socket timeouts by using RequestConfig.

RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(5000)
    .setSocketTimeout(5000)
    .build();

HttpPut request = new HttpPut(url);
request.setConfig(requestConfig);

Conclusion

Using Apache HttpClient to make a PUT HTTP request is straightforward and flexible. By following this tutorial, you should now be able to create and execute PUT requests, handle responses, and customize various aspects of the HTTP request and response process. Apache HttpClient provides a comprehensive set of features that make it an excellent choice for handling HTTP operations in Java applications. The JSONPlaceholder API serves as a practical and convenient source for testing and prototyping your HTTP requests.

Comments