Ask Your Question
0

How can one retrieve all headers using HttpClient?

asked 2021-08-15 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-04-18 01:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-15 11:00:00 +0000

Seen: 7 times

Last updated: Apr 18 '22