Apache HttpClient GET, POST, PUT and DELETE Methods Tutorial


In this tutorial, we will discuss how to use Apache HttpClient 4.5 to make an HTTP GET, POST, PUT, and DELETE requests.
HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GET, HEAD, POST, PUT, DELETE, TRACE, and OPTIONS. There is a specific class for each method type.: HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions.
In this example, we are going to use HttpGet, HttpPost, HttpPut, HttpDelete classes to handle GET, POST, PUT, DELETE HTTP Methods.

1. Create Simple Maven Project

Use Create Simple Maven Project in Eclipse tutorial to create a simple maven project in eclipse IDE.

2. Add Apache HttpClient Maven Dependency

The Apache HttpClient library allows handling HTTP requests. To use this library add a dependency to your Maven or Gradle build file. You find the latest version here: https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project.
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
</dependency>
Let's discuss each Http GET, POST, PUT, and DELETE methods with an example.

3. REST API Set up

Let's discuss how to use HttpClient in real-time projects. Consider we have deployed Spring boot Restful CRUD APIs. Check out this article - Spring Boot 2 + hibernate 5 + CRUD REST API Tutorial.
Let's write a REST Client to GET, POST, PUT, and DELETE Rest web services.
Make sure that your Spring boot application is up and running. Refer Spring Boot 2 + hibernate 5 + CRUD REST API Tutorial.

4. Http Post Method

Let's create a step by step example to make an HTTP POST request using HttpClient.

1. Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()
The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

2. Create a basic POST request

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");

3. Add headers to Post HTTP Request

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

3. Add JSON Data to Post request

String json = "{\r\n" + 
  "  \"firstName\": \"Ram\",\r\n" + 
  "  \"lastName\": \"Jadhav\",\r\n" + 
  "  \"emailId\": \"[email protected]\",\r\n" + 
  "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + 
  "  \"createdBy\": \"Ramesh\",\r\n" + 
  "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + 
  "  \"updatedby\": \"Ramesh\"\r\n" + 
  "}";
StringEntity stringEntity = new StringEntity(json);
httpPost.setEntity(stringEntity);

4. Create a custom response handler

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

5. Send basic POST request via execute() Method

String responseBody = httpclient.execute(httpPost, responseHandler);
In the following example, we send a resource to http://localhost:8080/api/v1/users. This resource accepts the request JSON, process it, and store it into a database. This service also returns a response with a resource. 

In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.

Here is the complete source code:
package net.javaguides.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpPost} request method.
 * @author Ramesh Fadatare
 */
public class HttpPostRequestMethodExample {

    public static void main(String[] args) throws IOException {
        postUser();
    }

    public static void postUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            String json = "{\r\n" +
                "  \"firstName\": \"Ram\",\r\n" +
                "  \"lastName\": \"Jadhav\",\r\n" +
                "  \"emailId\": \"[email protected]\",\r\n" +
                "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
                "  \"createdBy\": \"Ramesh\",\r\n" +
                "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
                "  \"updatedby\": \"Ramesh\"\r\n" +
                "}";
            StringEntity stringEntity = new StringEntity(json);
            httpPost.setEntity(stringEntity);

            System.out.println("Executing request " + httpPost.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

5. Http Get Method

Let's create a step by step example to make an HTTP GET request using HttpClient.

1. Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()
The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

2. Create a basic GET request

 HttpGet httpget = new HttpGet("http://httpbin.org/get");

3. Create a custom response handler

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

4. Send basic GET request via execute() method

String responseBody = httpclient.execute(httpget, responseHandler);

5. Get the Status Code of the HTTP Response

int status = response.getStatusLine().getStatusCode();

6. Get a response entity

HttpEntity entity = response.getEntity();
In the following example, we retrieve a resource from http://localhost:8080/api/v1/users/1.

In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.

Here is the complete source code:
package net.javaguides.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpGet} request method.
 * @author Ramesh Fadatare
 */
public class HttpGetRequestMethodExample {

    public static void main(String...args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://localhost:8080/api/v1/users/1");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

6. Http Put Method

Let's create a step by step example to make an HTTP PUT request using HttpClient.

1. Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()
The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

2. Create a basic PUT request

HttpPut httpPut = new HttpPut("http://localhost:8080/api/v1/users/1");

3. Add headers to PUT HTTP Request

HttpPut httpPut = new HttpPut("http://localhost:8080/api/v1/users/1");
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");

4. Add JSON Data to PUT request

String json = "{\r\n" + 
  "  \"firstName\": \"Ram\",\r\n" + 
  "  \"lastName\": \"Jadhav\",\r\n" + 
  "  \"emailId\": \"[email protected]\",\r\n" + 
  "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + 
  "  \"createdBy\": \"Ramesh\",\r\n" + 
  "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + 
  "  \"updatedby\": \"Ramesh\"\r\n" + 
  "}";
StringEntity stringEntity = new StringEntity(json);
httpPut.setEntity(stringEntity);

5. Create a custom response handler

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

6. Send a basic POST request via execute() Method

String responseBody = httpclient.execute(httpPut, responseHandler);
In the following example, we send a resource to http://localhost:8080/api/v1/users/1. This resource accepts the request JSON, process it, and store it into a database. This service also returns a response with an updated resource. 

In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.

Here is the complete source code:
package net.javaguides.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpPut} request method.
 * @author Ramesh Fadatare
 */

public class HttpPutRequestMethodExample {

    public static void main(String[] args) throws IOException {
        putUser();
    }

    public static void putUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPut httpPut = new HttpPut("http://localhost:8080/api/v1/users/1");
            httpPut.setHeader("Accept", "application/json");
            httpPut.setHeader("Content-type", "application/json");
            String json = "{\r\n" + "  \"firstName\": \"Ram\",\r\n" + "  \"lastName\": \"Jadhav\",\r\n" +
                "  \"emailId\": \"[email protected]\",\r\n" +
                "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + "  \"createdBy\": \"Ramesh\",\r\n" +
                "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + "  \"updatedby\": \"Ramesh\"\r\n" +
                "}";
            StringEntity stringEntity = new StringEntity(json);
            httpPut.setEntity(stringEntity);

            System.out.println("Executing request " + httpPut.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpPut, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

7. HTTP Delete Method

Let's create a step by step example to make an Http DELETE request using HttpClient.

Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()
The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

Create basic DELETE request

HttpDelete httpDelete = new HttpDelete("http://localhost:8080/api/v1/users/5");

Create a custom response handler

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

Send basic POST request via execute() Method

String responseBody = httpclient.execute(httpDelete, responseHandler);
In the following example, we are using http://localhost:8080/api/v1/users/1 Rest service to delete a user from a database with id 5. 

In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.

Here is the complete source code:
package net.javaguides.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpDelete} request method.
 * 
 * @author Ramesh Fadatare
 */
public class HttpDeleteRequestMethodExample {
    public static void main(String[] args) throws IOException {
        deleteUser();
    }

    public static void deleteUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            HttpDelete httpDelete = new HttpDelete("http://localhost:8080/api/v1/users/1");
            System.out.println("Executing request " + httpDelete.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpDelete, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}
Check out more examples on Apache HttpClient DELETE HTTP Request Example.
Check out how to use HttpClient with HTML Forms on Apache HttpClient HTML Form POST Request Example
Check out how to HttpClient with basic authentication on Apache HttpClient Basic Authentication Examples
Check out how to use HttpClient with File upload on Apache HttpClient Upload File Example

Comments

Post a Comment

Leave Comment