How do I Use HttpClient to Call REST APIs?

Java 11 introduced a new HttpClient API (java.net.HttpClient) that simplifies making HTTP requests and handling responses. It provides a clean and concise way to perform synchronous and asynchronous HTTP operations, and it fully supports RESTful APIs.

Here’s a step-by-step guide with examples for how to use the Java 11 HttpClient to call REST APIs.


1. Create an HttpClient Instance

The HttpClient is the main entry point for sending HTTP requests and receiving responses. You can create an HttpClient using its builder.

HttpClient client = HttpClient.newHttpClient();

2. Build an HttpRequest

The HttpRequest represents the HTTP request that you want to send. You can build it using a static builder where you set the HTTP method, headers, URI, etc.

Example: Build a GET Request

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
        .GET() // Use GET method
        .build();

Example: Build a POST Request

For a POST request, you also need to include a body in the request.

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"))
        .build();

3. Send the HttpRequest

The HttpClient provides methods to send HTTP requests. You can choose to execute the request synchronously or asynchronously.

Synchronous Call

Use HttpClient.send() to execute the request synchronously and retrieve an HttpResponse.

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());

Asynchronous Call

Use HttpClient.sendAsync() to execute the request asynchronously. It returns a CompletableFuture which allows non-blocking operations.

client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
      .thenApply(HttpResponse::body) // Extract body
      .thenAccept(System.out::println); // Print response body

The above code sends the request in the background and processes the response once received.


4. Handle Response

The HttpResponse provides access to the response details like status code, headers, and body. You can use HttpResponse.BodyHandlers to specify how the body should be processed.

Available BodyHandlers:

  • HttpResponse.BodyHandlers.ofString(): Read the response as a String.
  • HttpResponse.BodyHandlers.ofFile(): Save the response to a file.
  • HttpResponse.BodyHandlers.ofInputStream(): Access the response as an InputStream.

For example:

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Headers: " + response.headers());
System.out.println("Body: " + response.body());

5. Complete Example for a GET Request

Here’s a complete program that sends a GET request to a REST API and prints the response:

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientGetExample {
    public static void main(String[] args) {
        try {
            // Step 1: Create HttpClient
            HttpClient client = HttpClient.newHttpClient();

            // Step 2: Create HttpRequest
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                    .GET()
                    .build();

            // Step 3: Send the request and receive HttpResponse
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // Step 4: Process the response
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6. Complete Example for a POST Request

Here’s how you can do a POST request to send JSON data:

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientPostExample {
    public static void main(String[] args) {
        try {
            // Step 1: Create HttpClient
            HttpClient client = HttpClient.newHttpClient();

            // Step 2: Build HttpRequest with POST body
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString("{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"))
                    .build();

            // Step 3: Send the POST request and receive response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // Step 4: Process the response
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key Points to Remember:

  1. Use java.net.URI for specifying the API endpoint.
  2. Always handle exceptions (e.g., IOException and InterruptedException).
  3. You may need to set headers (e.g., Content-Type or Authorization) depending on the API requirements.
  4. Handle different response codes appropriately.

This approach is suitable for working with REST APIs and provides both blocking and non-blocking operations for flexibility.

How do I Send Requests Using Different HTTP Methods with HttpClient?

Java 11 introduced the HttpClient API to simplify and modernize HTTP communications. This API supports sending requests using different HTTP methods (GET, POST, PUT, DELETE, etc.). Below is an explanation and example of how to perform these operations.

1. Setup

You will use the HttpClient and related classes from java.net.http package:

  • HttpClient – To execute HTTP requests.
  • HttpRequest – To construct and describe HTTP requests.
  • HttpResponse – To handle HTTP responses.

2. Example Code

Here’s how you can send HTTP requests with different methods using HttpClient in Java 11.

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;

public class HttpClientMethodExample {
   public static void main(String[] args) {
      try {
         // Create an HttpClient instance
         HttpClient httpClient = HttpClient.newHttpClient();

         // Example: GET Request
         HttpRequest getRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .GET() // Default is GET, this is optional
                 .build();
         HttpResponse<String> getResponse = httpClient.send(getRequest, BodyHandlers.ofString());
         System.out.println("GET Response: " + getResponse.body());

         // Example: POST Request
         HttpRequest postRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts"))
                 .POST(BodyPublishers.ofString("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"))
                 .header("Content-Type", "application/json")
                 .build();
         HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
         System.out.println("POST Response: " + postResponse.body());

         // Example: PUT Request
         HttpRequest putRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .PUT(BodyPublishers.ofString("{\"id\":1,\"title\":\"updated\",\"body\":\"new content\",\"userId\":1}"))
                 .header("Content-Type", "application/json")
                 .build();
         HttpResponse<String> putResponse = httpClient.send(putRequest, BodyHandlers.ofString());
         System.out.println("PUT Response: " + putResponse.body());

         // Example: DELETE Request
         HttpRequest deleteRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .DELETE()
                 .build();
         HttpResponse<String> deleteResponse = httpClient.send(deleteRequest, BodyHandlers.ofString());
         System.out.println("DELETE Response Code: " + deleteResponse.statusCode());

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

3. Explanation

  1. HttpClient Creation: The HttpClient instance is reusable for making multiple requests.
  2. GET Request:
    • Use .GET() method to send a GET request.
    • Response is parsed as a String using BodyHandlers.ofString().
  3. POST Request:
    • Use .POST(BodyPublishers.ofString(content)) to send a POST request with a payload.
    • Set the Content-Type header for JSON or other content types.
  4. PUT Request:
    • Use .PUT(BodyPublishers.ofString(content)) for PUT requests with a payload.
    • Similar to POST, set the proper headers.
  5. DELETE Request:
    • Use .DELETE() to send DELETE requests.
    • Rarely includes a body; that’s why no publisher is used.
  6. Error Handling:
    • Be sure to include error handling for exceptions such as IOException and InterruptedException.

4. Output Example

If you run the code using the example endpoints, the output might look something like this:

GET Response: {
  "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 Response: {
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}
PUT Response: {
  "id": 1,
  "title": "updated",
  "body": "new content",
  "userId": 1
}
DELETE Response Code: 200

5. Notes

  • You’ll need an API endpoint that supports CRUD operations for realistic testing.
  • Avoid hardcoding URIs in production; keep them configurable.
  • Handle response status codes appropriately for error cases (like 404, 500).

This approach provides a clean and modern way to work with HTTP in Java!

How do I handle GET and POST requests in Jakarta Servlets?

Handling GET and POST requests in Jakarta Servlets involves overriding the doGet() and doPost() methods provided by the HttpServlet class. Here’s a step-by-step guide:


1. Import Necessary Packages

First, ensure you import the jakarta.servlet and jakarta.servlet.http packages in your servlet class.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

2. Create a Servlet Class

Your servlet class should extend the HttpServlet class. The doGet() method will handle GET requests, while the doPost() method will handle POST requests.


3. Override doGet and doPost Methods

  • Use the HttpServletRequest object to get request data.
  • Use the HttpServletResponse object to send a response to the client.

4. Example Code

Here’s a complete example:

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/example")  // Annotation to map this servlet to "/example"
public class ExampleServlet extends HttpServlet {

    // Handles GET requests
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");

        // Get query parameter (e.g., ?name=John)
        String name = request.getParameter("name");

        // Prepare response
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Hello, " + (name != null ? name : "Guest") + "!</h1>");
        out.println("<form method='POST' action='/example'>");
        out.println("<label for='postName'>Enter your name:</label>");
        out.println("<input type='text' id='postName' name='name'>");
        out.println("<button type='submit'>Submit</button>");
        out.println("</form>");
        out.println("</body></html>");
    }

    // Handles POST requests
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");

        // Get form data (e.g., from POST body)
        String name = request.getParameter("name");

        // Prepare response
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Thank you, " + (name != null ? name : "Guest") + "!</h1>");
        out.println("<a href='/example'>Go back</a>");
        out.println("</body></html>");
    }
}

5. Explanation

  • Annotations: The @WebServlet("/example") annotation maps this servlet to the /example URL.
  • GET and POST
    • The doGet() method handles requests sent as GET, typically used when the client fetches data.
    • The doPost() method handles requests sent as POST, commonly used to send form data to the server.
  • Parameters: Use request.getParameter("paramName") to retrieve parameters from the request.

6. Deploy and Test

  1. Add the servlet to your Jakarta EE web application.
  2. Access the servlet:
    • GET request: Open `http://localhost:8080/your-app-context/example` in a browser.
    • POST request: Submit the HTML form created in doGet() or use a tool like Postman.

7. Keynotes

  • Always handle exceptions (IOException and ServletException) properly in production.
  • Use appropriate HTTP response headers and status codes.
  • Consider character encoding (request.setCharacterEncoding("UTF-8") and response.setCharacterEncoding("UTF-8")) for supporting special characters.

This is how you handle GET and POST requests in a Jakarta Servlet effectively!

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How do I send a POST request with JSON data using Java 11 HttpClient?

In Java 11, the HttpClient API was introduced as part of JEP 321, providing a standardized way to perform HTTP operations. To send a POST request with JSON data, you can use the HttpClient along with its HttpRequest object. Here’s a step-by-step guide and example:

Steps to Send POST Request with JSON Data in Java 11

  1. Create an instance of HttpClient:
    HttpClient is used to send HTTP requests and receive responses.

  2. Build the HttpRequest:
    Use the HttpRequest class to set the URI, HTTP method (POST), and add the JSON payload as the request body.

  3. Set the Content Type Header:
    Use the Content-Type header to specify that the content type of the request body is JSON.

  4. Send the request and handle the response:
    Use the HttpClient‘s send or sendAsync method to execute the request and retrieve the response.

Java Example: Sending a POST Request with JSON Data

package org.kodejava.net.http;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class PostRequestExample {

   public static void main(String[] args) {
      // 1. Create HttpClient instance
      try (HttpClient httpClient = HttpClient.newHttpClient()) {

         // 2. JSON data to send in the POST request
         String json = """
                 {
                     "title": "nesciunt quas odio",
                     "body": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
                     "userId": 1
                 }
                 """;

         // 3. Create HttpRequest and set headers
         HttpRequest request = HttpRequest.newBuilder()
                 .uri(URI.create("https://jsonplaceholder.typicode.com/posts/")) // Replace with your API endpoint
                 .header("Content-Type", "application/json")       // Set content type to JSON
                 .POST(HttpRequest.BodyPublishers.ofString(json))  // Set the JSON as body
                 .build();

         try {
            // 4. Send the request and get HttpResponse
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            // 5. Process the response
            if (response.statusCode() == 200 || response.statusCode() == 201) {
               System.out.println("Response: " + response.body());
            } else {
               System.err.println("Failed with HTTP error code: " + response.statusCode());
            }
         } catch (IOException | InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

Breakdown of the Example:

  1. Create HttpClient:

    HttpClient httpClient = HttpClient.newHttpClient();
    

    This creates a new instance of the HttpClient, which will be used to send/receive requests.

  2. JSON Payload:
    A JSON string is created using Java’s multi-line string feature ("""), available starting from Java 13. Alternatively, you can concatenate strings or use external libraries like Jackson to generate the JSON.

  3. Build HttpRequest:

    HttpRequest request = HttpRequest.newBuilder()
           .uri(URI.create("https://jsonplaceholder.typicode.com/posts/"))
           .header("Content-Type", "application/json")
           .POST(HttpRequest.BodyPublishers.ofString(json))
           .build();
    
    • .uri(URI): Specifies the URI (endpoint) for the request.
    • .header("Content-Type", "application/json"): Adds a header specifying the content type.
    • .POST(HttpRequest.BodyPublishers.ofString(json)): Sets the request method to POST and attaches the JSON string as the body.
  4. Send Request and Receive Response:
    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    
    • httpClient.send: Performs the HTTP request.
    • HttpResponse.BodyHandlers.ofString(): Specifies that the response body should be treated as a String.
  5. Handle the Response:
    The response status code and body are processed accordingly (response.statusCode() and response.body()).

Sample Output

If the request is successful, you might see output like:

Response: {
  "title": "nesciunt quas odio",
  "body": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "userId": 1,
  "id": 101
}

Notes:

  1. Replace the URL (`https://jsonplaceholder.typicode.com/posts/`) with the actual endpoint you want to call.
  2. Add error handling and retries as needed for production environments.
  3. If advanced JSON manipulation is required, consider using libraries like Jackson or Gson to build the JSON payload programmatically.

Dependencies

No external dependencies are required; this is achievable with core Java 11+ classes.

How do I send an HTTP POST request?

The following code snippet will show you how to send an HTTP post request using the Apache HttpComponents. We will send a post request to https://httpbin.org/post, with some parameters to the request using the NameValuePair object.

To pass these parameters to the HTTP post request we create an instance of UrlEncodedFormEntity and pass a list of NameValuePair as the arguments. And before executing the request we set this entity object to the HttpPost.setEntity() method.

Let’s see the code below:

package org.kodejava.apache.http;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpPostExample {
    public static void main(String[] args) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpPost post = new HttpPost("https://httpbin.org/post");

            // Create some NameValuePair for HttpPost parameters
            List<NameValuePair> arguments = new ArrayList<>(3);
            arguments.add(new BasicNameValuePair("username", "admin"));
            arguments.add(new BasicNameValuePair("firstName", "System"));
            arguments.add(new BasicNameValuePair("lastName", "Administrator"));


            post.setEntity(new UrlEncodedFormEntity(arguments));
            HttpResponse response = client.execute(post);

            // Print out the response message
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

Maven Central