How would you add custom HTTP headers (like an Authorization bearer token) to an outgoing request using HttpRequest.Builder?
Short answer
HttpRequest.Builder's header(name, value) method (called once per header, or headers(String...) for multiple at once) lets you attach any custom HTTP header to an outgoing request, commonly used for authentication (Authorization: Bearer token), content negotiation (Accept…
Advertisement
AModel answer
HttpRequest.Builder's header(name, value) method (called once per header, or headers(String...) for multiple at once) lets you attach any custom HTTP header to an outgoing request, commonly used for authentication (Authorization: Bearer token), content negotiation (Accept, Content-Type), or custom API-specific headers -- multiple calls to header() with the same name typically add multiple values for that header (following HTTP's own semantics for repeatable headers) rather than overwriting a previous value, an important distinction from some other HTTP client libraries' differing conventions.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/protected"))
.header("Authorization", "Bearer " + accessToken)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());Real-world example
An API client authenticating with a bearer token attaches it via the Authorization header on every outgoing request using HttpRequest.Builder's header() method, following the standard OAuth2 bearer token convention that the target API expects for authenticating each individual request.
Likely follow-ups
- How would you set a default set of headers to apply to every request sent through a given HttpClient, without repeating them on each individual HttpRequest.Builder call?
- What happens if you call header() twice with the same header name -- does the second call overwrite the first?
Related topics