Ask Your Question

Revision history [back]

To retrieve all headers using HttpClient, one can use the following code:

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class TestHttpClient {
    public static void main(String[] args) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet();
        request.setURI(URI.create("http://example.com"));

        HttpResponse response = httpClient.execute(request);

        System.out.println("Status code: " + response.getStatusLine().getStatusCode());

        System.out.println("Headers: ");
        Arrays.stream(response.getAllHeaders())
            .forEach(h -> System.out.println(h.getName() + " : " + h.getValue()));

        String responseText = EntityUtils.toString(response.getEntity());
        System.out.println("Response: " + responseText);
    }
}

In this code, the HttpClient is created using HttpClients.createDefault(). An HTTP GET request is created using HttpGet, and the URI is set to http://example.com.

The request is executed using httpClient.execute(request) which returns an HttpResponse object.

The status code of the response is printed first using response.getStatusLine().getStatusCode().

The headers of the response are printed using response.getAllHeaders(). The Arrays.stream().forEach() method is used to iterate over all the headers and print their name and value.

Finally, the response body is extracted using EntityUtils.toString(response.getEntity()) and printed to the console.