使用apache httpclient 4显示请求标头时出现问题

时间:2010-08-15 22:38:22

标签: java http httpclient

我一直在尝试使用HttpClient 4检索HttpMethod发送的标头,但没有任何成功......

这是我的代码:

HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParams = httpClient.getParams();
HttpGet httpGet = new HttpGet("http://www.google.fr");

HttpResponse response = httpClient.execute(httpGet);

log.info("*** Request headers ***");
Header[] requestHeaders = httpGet.getAllHeaders();
for(Header header : requestHeaders) {
    log.info(header.toString());
}
log.info("***********************");


log.info("*** reponse ***");
log.info(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for(Header header : headers) {
    log.info(header.toString());
}

但结果是:

00:27:57,368 INFO   - *** Request headers ***

00:27:57,368 INFO   - ***********************

00:27:57,368 INFO   - *** reponse ***

00:27:57,368 INFO   - HTTP/1.1 200 OK

00:27:57,368 INFO   - Date: Sun, 15 Aug 2010 22:28:09 GMT

00:27:57,368 INFO   - Expires: -1

00:27:57,368 INFO   - Cache-Control: private, max-age=0

00:27:57,368 INFO   - Content-Type: text/html; charset=ISO-8859-1

00:27:57,368 INFO   - Set-Cookie: 

[..]

Aka的响应头很好,但不是请求的。 (如果我在执行语句之前移动日志请求标头块,结果相同)。

(不,我不想简单地看到它们,所以将日志级别设置为调试是不可接受的)

任何人都可以提供帮助吗?

3 个答案:

答案 0 :(得分:8)

要获取所有标题,包括HTTPclient设置的标题,请使用
HttpCoreContext。该类允许读出所有标题。

HttpClient client = HttpClients.createDefault();
HttpCoreContext localContext = new HttpCoreContext();
HttpResponse response = client.execute(request,localContext);

Header[] headers = localContext.getRequest().getAllHeaders();
for (Header header : headers) {
   System.out.println(header.toString());
}

答案 1 :(得分:4)

自2010年以来情况可能已发生变化,但这可以通过使用请求拦截器(以更低级别检查请求)和令人惊讶的相似代码来完成。

// So we can get all the headers (not just the ones we explicitly set).        
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

    public void process(
            final HttpRequest request,
            final HttpContext context) 
            throws HttpException, IOException {

        // Start Debug
        System.out.println("*** Request headers ***");
        Header[] requestHeaders = request.getAllHeaders();
        for(Header header : requestHeaders) {
            System.out.println(header.toString());
        }
        System.out.println("***********************");
        // End Debug
    }

});

在我的情况下,我得到以下输出(仅显式设置其中两个)。

*** Request headers ***
Accept: application/xml
Authorization: Basic bmV3Omd1ZXN0
Content-Length: 772
Content-Type: application/xml; charset=UTF-8
Host: rest3api.sifassociation.org:80
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)
***********************

这可以帮助那些在这里旅行的人。

答案 2 :(得分:2)

它只显示您自己设置的请求标题。

如果要记录HttpClient设置的请求标头,则需要按Commons Logging配置HttpClient的内置日志记录。另请参阅this document

作为替代方案,您还可以使用Fiddler等外部工具。