Add a Custom HTTP Header with the HttpClient

HTTP headers let the client and the server pass additional information with an HTTP request or response. Here, you will learn to add a custom HTTP header with the HttpClient.

We will use the Apache HttpClient, the most widely used HTTP client in Java.

Add a Custom HTTP Header with the HttpClient

In this example program, we will execute an HTTP GET request and add some custom headers.

import org.apache.http.HttpResponse;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


public class Test {

  public static void main(String[] args) throws IOException {

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      HttpUriRequest request = RequestBuilder.get()
              // adding headers
              .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
              .setHeader("Authorization", "Bearer 123token")

      System.out.println("Executing GET request...");
      HttpResponse response = httpclient.execute(request);

      String responseString = new BasicResponseHandler().handleResponse(response);

      System.out.println("Response: " + responseString);
Output: Executing GET request… Response: { “userId”: 1, “id”: 1, “title”: “delectus aut autem”, “completed”: false }

We used the RequestBuilder class to specify URI and headers needed for the request.

There is also a way to set the default headers. 

Set default headers on the HTTP client in Java

Instead of setting the same headers on every request, we can set default headers that will be added to each request automatically.

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.*;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicHeader;

import java.util.Arrays;

public class Test {

  public static void main(String[] args) throws IOException {

    // create custom headers
    Header contentTypeHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    Header authorizationHeader = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer 123token");

    List<Header> headers = Arrays.asList(contentTypeHeader, authorizationHeader);

    // set custom headers as default headers
    HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();

    HttpUriRequest request = RequestBuilder.get().setUri("url").build();

I hope this tutorial was of some help to you. If you work with HttpClient then you might also be interested in learning how to configure HttpClient to accept all SSL certificates

Happy learning!

Leave a Reply

Your email address will not be published. Required fields are marked *