Apache HttpClient GET, POST, PUT and DELETE Methods Tutorial

Introduction

Apache HttpClient is a versatile and powerful library for handling HTTP requests in Java. It supports various HTTP methods, including GET, POST, PUT, DELETE, and more. This tutorial will demonstrate how to use Apache HttpClient to perform GET, POST, PUT, and DELETE requests.

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 simple Java classes that perform GET, POST, PUT, and DELETE requests to specified URLs and print the responses.

JSONPlaceholder API

For demonstration purposes, we'll use the JSONPlaceholder API, which provides fake online RESTful endpoints for testing and prototyping.

GET Request

Java Class for Sending GET Request

Create a class named HttpClientGetExample with the following code:

import org.apache.hc.client5.http.classic.methods.HttpGet;
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.EntityUtils;

public class HttpClientGetExample {

    public static void main(String[] args) {
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        
        // Create HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            
            // Create HttpGet request
            HttpGet request = new HttpGet(url);
            
            // 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();
        }
    }
}

Example Output

Response Code: 200
Response Content: 
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit...
}

POST Request

Java Class for Sending POST Request

Create a class named HttpClientPostExample with the following code:

import org.apache.hc.client5.http.classic.methods.HttpPost;
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 HttpClientPostExample {

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

        // Create HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            
            // Create HttpPost request
            HttpPost request = new HttpPost(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();
        }
    }
}

Example Output

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

PUT Request

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();
        }
    }
}

Example Output

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

DELETE Request

Java Class for Sending DELETE Request

Create a class named HttpClientDeleteExample with the following code:

import org.apache.hc.client5.http.classic.methods.HttpDelete;
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.EntityUtils;

public class HttpClientDeleteExample {

    public static void main(String[] args) {
        String url = "https://jsonplaceholder.typicode.com/posts/1";

        // Create HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            
            // Create HttpDelete request
            HttpDelete request = new HttpDelete(url);
            
            // 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();
        }
    }
}

Example Output

Response Code: 200
Response Content: 
{}

Additional Configuration

Setting Custom Headers

You can set custom headers for the requests by using the setHeader method on the request objects (HttpGet, HttpPost, HttpPut, HttpDelete).

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();

request.setConfig(requestConfig);

Conclusion

Using Apache HttpClient to make GET, POST, PUT, and DELETE HTTP requests is straightforward and flexible. By following this tutorial, you should now be able to create and execute these types of 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

Post a Comment

Leave Comment