How can I display all the HTTP Headers when using the DefaultHTTPClient?

后端 未结 5 964
太阳男子
太阳男子 2020-12-30 12:21

When using the DefaultHttpClient() from the Apache Commons HTTP Client, is it possible to show the full request in the console output for debugging purposes?

相关标签:
5条回答
  • 2020-12-30 13:02

    From another answer on StackOverflow. This can easily be done by enabling the debug logging for the Apache HTTP Client:

    java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINEST);
    java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.FINEST);
    
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "debug");
    
    0 讨论(0)
  • 2020-12-30 13:04

    Yes, here's sample code:

        import java.util.Arrays;
        import org.apache.http.Header;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpGet;
        ...
        HttpResponse response;
        ...
        HttpGet httpGet = new HttpGet(serviceURL);
        response = httpclient.execute(httpGet);
        ...
        // Print all headers
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());        
        for (Header header : httpHeaders) {
            System.out.println("Headers.. name,value:"+header.getName() + "," + header.getValue());
        }
    
    0 讨论(0)
  • 2020-12-30 13:11

    When you execute the request you are passing somewhere HttpRequest object. It has method getAllHeaders()

    0 讨论(0)
  • 2020-12-30 13:14

    You can get all headers like this:

    Enumeration headerNames = request.getHeaderNames();
    while(headerNames.hasMoreElements()) {
      String headerName = (String)headerNames.nextElement();
      out.println("" + headerName);
      out.println("" + request.getHeader(headerName));
    }
    

    See this tutorial for more info.

    0 讨论(0)
  • 2020-12-30 13:14

    If you are using Logback as your logging framework, add the following configuration to your logback.xml / logback-test.xml file:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <configuration scan="true">
    
        <!-- more config -->
    
        <logger name="org.apache.http" level="DEBUG"/>
    
        <!-- more config -->
    
    </configuration>
    

    Having added this configuration, Logback's log appenders will now show useful HttpClient-related information about HTTP request and response headers, among other things.

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