开发者

Get header from HttpResponse in Android

开发者 https://www.devze.com 2023-03-14 14:35 出处:网络
Is there a way to get the value of a specific header using the HttpResponse object returned by the HttpClient execute() method in Andr开发者_StackOverflowoid?There are several ways to get specific hea

Is there a way to get the value of a specific header using the HttpResponse object returned by the HttpClient execute() method in Andr开发者_StackOverflowoid?


There are several ways to get specific headers. HttpResponse inherits from HttpMessage, which provides the following header retrieval methods:

  • Header getFirstHeader(String name)
  • Header[] getHeaders(String name)
  • Header getLastHeader(String name)

In your case, you probably want getFirstHeader(String). Headers can contain multiple values, hence the Header[] array return from getHeaders(); if you only expect there to be a single header, getFirstHeader(String) should suffice.


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


Have you tried HttpResponse.getHeaders() method?


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/


Please try HttpResponse.getAllHeaders() for printing headers and for printing cookie in Headers.

response.getHeaders("Set-Cookie")
0

精彩评论

暂无评论...
验证码 换一张
取 消