2010-08-15 93 views
2

我一直在試圖獲取由列舉HTTPMethod發送的頭,使用HttpClient的4,但沒有任何成功...問題顯示請求頭與Apache HttpClient的4

這裏是我的代碼:

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: 

[..] 

阿卡響應報頭是好的,但不是要求的。 (如果我在執行語句之前移動日誌請求頭塊,結果相同)。

(不,我不想只看到他們,所以設置日誌級別調試心不是可以接受的)

任何人都可以幫助嗎?

回答

1

它只會顯示您自己設置的請求標頭。

如果你想記錄HttpClient設置的請求頭,那麼你需要配置HttpClient的內置日誌記錄Commons Logging。另見this document

作爲替代方案,您還可以使用外部工具,如Fiddler

+0

感謝您的回答,但我說更改日誌級別不可接受:我需要存儲發送的標頭。您確定在執行請求之前甚至之後無法獲取它們? – 2010-08-16 07:57:51

3

事情自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) 
*********************** 

這可以幫助那些在這裏旅行的人。

6

要獲取所有標頭,包括HTTP客戶端設置的標頭,請使用
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()); 
} 
+0

這應該是正確的答案 – Jansen 2016-10-30 14:21:57