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
- Create HttpClient: The
HttpClient
is created usingHttpClient.newHttpClient()
. - 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.).
- Use
-
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 sameHttpRequest.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.
Latest posts by Wayan (see all)
- How do I secure servlets with declarative security in web.xml - April 24, 2025
- How do I handle file uploads using Jakarta Servlet 6.0+? - April 23, 2025
- How do I serve static files through a Jakarta Servlet? - April 23, 2025