How do I send a simple GET request using Java 11 HttpClient?

In Java 11, you can use the HttpClient to send HTTP requests easily. Here’s how you can send a simple GET request using HttpClient:

Full Example:

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 SimpleGetRequestExample {

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

         // Create the GET request
         HttpRequest request = HttpRequest.newBuilder()
                 .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")) // Replace with your URL
                 .GET() // Optional since GET is the default
                 .build();

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

         // Print the response status and body
         System.out.println("Status code: " + response.statusCode());
         System.out.println("Response body: " + response.body());

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

Explanation:

  1. HttpClient Instance:
    • Use HttpClient.newHttpClient() to create a new HttpClient. You can also customize the client for specific timeouts, authentication, or proxy configurations.
  2. HttpRequest Object:
    • Use HttpRequest.newBuilder() to create a request.
    • Use .uri(URI.create("URL")) to set the target URI.
    • Specify the HTTP method using .GET() (which is the default for HttpRequest).
  3. Send the HTTP Request:
    • Use the httpClient.send(request, HttpResponse.BodyHandlers.ofString()) method.
    • HttpResponse.BodyHandlers.ofString() specifies how the response body should be handled (in this case, as a string).
  4. Process the Response:
    • Access the HTTP response status code using response.statusCode().
    • Access the body using response.body().

Output for the Example:

If the request is successful, you would see the HTTP status code (e.g., 200) and the response body for the given URL printed in the console.

Status code: 200
Response body: {
  "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"
}

Alternative: Using Asynchronous Request

If you want to send the request asynchronously:

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.util.concurrent.CompletableFuture;

public class AsyncGetRequestExample {

   public static void main(String[] args) {
      HttpClient httpClient = HttpClient.newHttpClient();

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

      CompletableFuture<HttpResponse<String>> responseFuture = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString());

      responseFuture.thenAccept(response -> {
         System.out.println("Status code: " + response.statusCode());
         System.out.println("Response body: " + response.body());
      }).join(); // Waits for the asynchronous computation to complete
   }
}

Benefits of Using HttpClient in Java 11:

  • Built-in support for HTTP/1.1 and HTTP/2.
  • Synchronous (send) and asynchronous (sendAsync) request capabilities.
  • Configurable features like timeouts and proxy settings.

By following these examples, you can handle simple GET requests in Java 11 effectively!

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.