Get header from HttpResponse in Android

2019-02-09 03:54发布

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

5条回答
倾城 Initia
2楼-- · 2019-02-09 04:26

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

response.getHeaders("Set-Cookie")
查看更多
别忘想泡老子
3楼-- · 2019-02-09 04:32

Have you tried HttpResponse.getHeaders() method?

查看更多
冷血范
4楼-- · 2019-02-09 04:37

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/

查看更多
Anthone
5楼-- · 2019-02-09 04:39

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

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.

查看更多
太酷不给撩
6楼-- · 2019-02-09 04:39

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

查看更多
登录 后发表回答