SoFunction
Updated on 2025-03-04

How to use Apache HttpClient to execute GET, POST, PUT and DELETE requests

Apache HttpClient is a powerful and flexible library for handling HTTP requests in Java.

It supports a variety of HTTP methods, including GET, POST, PUT and DELETE.

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 toAdd the following dependencies to the file:

<!-- /artifact/.client5/httpclient5 -->
<dependency>
    <groupId>.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>

Sample Scenario

We will create simple Java classes that will send GET, POST, PUT, and DELETE requests to the specified URL and print the response.

JSONPlaceholder API

For demonstration purposes, we will use the JSONPlaceholder API, which provides a virtual online RESTful endpoint for testing and prototyping.

GET Request

Java class that sends GET requests

Create a name calledHttpClientGetExampleThe code of the class is as follows:

import .;
import .;
import .;
import .;
import .;
public class HttpClientGetExample {
    public static void main(String[] args) {
        String url = "/posts/1";
        // Create HttpClient        try (CloseableHttpClient httpClient = ()) {
            // Create an HttpGet request            HttpGet request = new HttpGet(url);
            // Execute the request            try (CloseableHttpResponse response = (request)) {
                // Get HTTP response status                ("Response Code: " + ());
                // Get HTTP response content                String content = (());
                ("Response Content: \n" + content);
            }
        } catch (Exception e) {
            ();
        }
    }
}

Sample 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 recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

POST request

Java class that sends POST request

Create a name calledHttpClientPostExampleThe code of the class is as follows:

import .;
import .;
import .;
import .;
import .;
import .;
import .;
public class HttpClientPostExample {
    public static void main(String[] args) {
        String url = "/posts";
        String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        // Create HttpClient        try (CloseableHttpClient httpClient = ()) {
            // Create an HttpPost request            HttpPost request = new HttpPost(url);
            // Set JSON load            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            (entity);
            // Set the header            ("Accept", "application/json");
            ("Content-type", "application/json");
            // Execute the request            try (CloseableHttpResponse response = (request)) {
                // Get HTTP response status                ("Response Code: " + ());
                // Get HTTP response content                String content = (());
                ("Response Content: \n" + content);
            }
        } catch (Exception e) {
            ();
        }
    }
}

Sample output

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

PUT Request

Java class that sends PUT requests

Create a name calledHttpClientPutExampleThe code of the class is as follows:

import .;
import .;
import .;
import .;
import .;
import .;
import .;
public class HttpClientPutExample {
    public static void main(String[] args) {
        String url = "/posts/1";
        String json = "{\"id\":1,\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        // Create HttpClient        try (CloseableHttpClient httpClient = ()) {
            // Create an HttpPut request            HttpPut request = new HttpPut(url);
            // Set JSON load            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            (entity);
            // Set the header            ("Accept", "application/json");
            ("Content-type", "application/json");
            // Execute the request            try (CloseableHttpResponse response = (request)) {
                // Get HTTP response status                ("Response Code: " + ());
                // Get HTTP response content                String content = (());
                ("Response Content: \n" + content);
            }
        } catch (Exception e) {
            ();
        }
    }
}

Sample output

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

DELETE request

Java class that sends DELETE requests

Create a name calledHttpClientDeleteExampleThe code of the class is as follows:

import .;
import .;
import .;
import .;
import .;
public class HttpClientDeleteExample {
    public static void main(String[] args) {
        String url = "/posts/1";
        // Create HttpClient        try (CloseableHttpClient httpClient = ()) {
            // Create an HttpDelete request            HttpDelete request = new HttpDelete(url);
            // Execute the request            try (CloseableHttpResponse response = (request)) {
                // Get HTTP response status                ("Response Code: " + ());
                // Get HTTP response content                String content = (());
                ("Response Content: \n" + content);
            }
        } catch (Exception e) {
            ();
        }
    }
}

Sample output

Response Code: 200
Response Content: 
{}

Additional configuration

  • Setting up custom headers: It can be called on the request object (such as HttpGet, HttpPost, HttpPut, HttpDelete)setHeaderMethod to set custom headers.
  • Handle redirects: By default, Apache HttpClient will automatically handle redirects. You can use customHttpClientBuilderCustomize this behavior.
  • Set timeout: Can be usedRequestConfigto set connection and socket timeouts.

in conclusion

It is very convenient to use Apache HttpClient to perform GET, POST, PUT, and DELETE HTTP requests.

By following this tutorial, you should now be able to create and execute these types of requests, process responses, and customize HTTP requests and response procedures.

Apache HttpClient provides a complete set of features that make it an excellent choice for handling HTTP operations in Java applications.

The JSONPlaceholder API is a practical and convenient source for testing and prototype your HTTP requests.

This is the article about how to use Apache HttpClient to execute GET, POST, PUT and DELETE requests. For more related contents of Apache HttpClient to execute GET, POST, PUT and DELETE requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!