Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get header from HttpResponse in Android

Is there a way to get the value of a specific header using the HttpResponse object returned by the HttpClient execute() method in Android?

like image 937
Radu Stoenescu Avatar asked Jun 21 '11 11:06

Radu Stoenescu


People also ask

How to get header value from HttpResponse in Java?

Simple Way to Get HTTP Response Header in Java – conn. getHeaderFields() public Map<String,List<String>> getHeaderFields() Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent the response-header field names.

How to get HTTP response object in Java?

A HttpResponse is available when the response status code and headers have been received, and typically after the response body has also been received. This depends on the response body handler provided when sending the request. In all cases, the response body handler is invoked before the body is read.

What is the advantage of ETag response header in a response message?

The ETag (or entity tag) HTTP response header is an identifier for a specific version of a resource. It lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content was not changed.


2 Answers

try the below method :-

URL obj = new URL("http://mkyong.com");
    URLConnection conn = obj.openConnection();
    Map<String, List<String>> map = conn.getHeaderFields();

    System.out.println("Printing Response Header...\n");

    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() 
                           + " ,Value : " + entry.getValue());
    }

    System.out.println("\nGet Response Header By Key ...\n");
    String server = conn.getHeaderField("Server");

    if (server == null) {
        System.out.println("Key 'Server' is not found!");
    } else {
        System.out.println("Server - " + server);
    }

    System.out.println("\n Done");

    } catch (Exception e) {
    e.printStackTrace();
    }

http://www.mkyong.com/java/how-to-get-http-response-header-in-java/

like image 172
duggu Avatar answered Sep 19 '22 18:09

duggu


I always use this code

Initially, I do so

 Header[] headers = response.getAllHeaders();

Next, I'm using a simple method converts in hashmap

 private HashMap<String, String> convertHeadersToHashMap(Header[] headers) {
    HashMap<String, String> result = new HashMap<String, String>(headers.length);
    for (Header header : headers) {
        result.put(header.getName(), header.getValue());
    }
    return result;
}

Now I can get any value

Maybe someone can help Good luck

like image 42
Sergei S Avatar answered Sep 19 '22 18:09

Sergei S