coffeelemon
coffeelemon

Reputation: 21

How to get specific HTTP header values from an HTTP response in Java?

For example, you can extract the status code from a CloseableHTTPResponse using response.getStatusLine().getStatusCode().

Is there a similar way to get a specific header value (ie. Location, Date, etc.) from the response (in String format)?

Upvotes: 2

Views: 15156

Answers (1)

Gabriel Granados.
Gabriel Granados.

Reputation: 41

You can do it using getFirstHeader("key").

Apache HttpClient example:

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://api.com");
HttpResponse response = client.execute(request);

//get header by 'key'
String headerName= response.getFirstHeader("headerName").getValue();

If you want to get all the headers, you can use getAllHeaders().

//get all headers       
    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName() 
              + " ,Value : " + header.getValue());
    }

Upvotes: 4

Related Questions