Get header from HttpResponse in Android

后端 未结 5 1998
醉话见心
醉话见心 2020-12-31 09:56

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

相关标签:
5条回答
  • Have you tried HttpResponse.getHeaders() method?

    0 讨论(0)
  • 2020-12-31 10:37

    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.

    0 讨论(0)
  • 2020-12-31 10:37

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

    response.getHeaders("Set-Cookie")
    
    0 讨论(0)
  • 2020-12-31 10:44

    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

    0 讨论(0)
  • 2020-12-31 10:47

    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/

    0 讨论(0)
提交回复
热议问题