How do I set custom headers in Java 11 HttpRequest?

In Java 11, the java.net.http package introduced the new HttpClient API, which simplifies working with HTTP requests and responses. To set custom headers for an HttpRequest, you can use the headers method or the setHeader method while building your request using the HttpRequest.Builder.

Here’s a step-by-step guide for setting custom headers:

Example Code

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

   public static void main(String[] args) throws Exception {
      // Create an HttpClient
      HttpClient client = HttpClient.newHttpClient();

      // Create a request with custom headers
      HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create("https://example.com"))
              .header("Custom-Header", "HeaderValue") // Set custom single header
              .headers("Another-Header", "AnotherValue", "Yet-Another-Header", "YetAnotherValue") // Multiple headers
              .GET() // Specify HTTP method
              .build();

      // Send the request and print the response
      HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
      System.out.println("Response code: " + response.statusCode());
      System.out.println("Response body: " + response.body());
   }
}

Key Points in the Code

  1. Create HttpClient: The HttpClient is created using HttpClient.newHttpClient().
  2. Building the Request:
    • Use .header(String name, String value) to set a single custom header.
    • Use .headers(String... headers) to set multiple custom headers. Pass alternating key-value pairs as arguments.
    • Specify the URI and the HTTP method (GET, POST, etc.).
  3. Send the Request: The HttpClient sends the request using the .send() method and handles the response.

Notes:

  • Headers get overridden: If you call .header or .headers multiple times on the same HttpRequest.Builder, later calls for the same key will replace previous header values.
  • Thread Safety: The HttpClient instance is immutable and thread-safe, so you can reuse it for multiple requests.
  • Custom Headers: Use custom headers for tasks like authentication (e.g., Authorization headers), caching, or API versioning.
Wayan

Leave a Reply

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