2012-02-03 31 views
4

響應頭,我試圖用HTTP單元讀取響應頭爲我的應用 -閱讀使用的HtmlUnit

WebClient webClient = new WebClient(); 
WebClient.setThrowExceptionOnScriptError(false); 
HtmlPage currentPage = webClient.getPage("http://myapp.com"); 
WebResponse response = currentPage.getWebResponse(); 
System.out.println(response.getResponseHeaders()); 

我能看到的響應頭,但它們僅限於第一HTTP GET請求。 當我使用LiveHTTPHeaders插件的Firefox插件時,我得到了所有的獲取請求和相應的標題響應。

有沒有什麼辦法讓所有後續請求的http頭不受限制只是第一次得到?

回答

6
List<NameValuePair> response =currentPage.getWebResponse().getResponseHeaders(); 
for (NameValuePair header : response) { 
    System.out.println(header.getName() + " = " + header.getValue()); 
} 

適合我。

1

AFAIK,這應該工作:

WebClient webClient = new WebClient(); 
WebClient.setThrowExceptionOnScriptError(false); 
HtmlPage currentPage = webClient.getPage("http://myapp.com"); 
WebResponse response = currentPage.getWebResponse(); 
System.out.println(response.getResponseHeaders()); 
// And even in subsequent requests 
currentPage = webClient.getPage("http://myapp.com"); 
response = currentPage.getWebResponse(); 
System.out.println(response.getResponseHeaders()); 

這是否代碼工作?如果是這樣,那麼你可能沒有正確分配currentPage變量,所以它保持原始值。

+0

我在使用Selenium使用捕捉N/W流量結束了。 – Tarun 2012-02-06 10:22:28

+0

我不知道爲什麼我得到了這個downvote ... – 2012-06-21 15:30:16

+0

我沒有downvote – Tarun 2012-06-22 04:27:01

2

這裏是一個簡潔的例子從一個的HtmlUnit響應顯示所有的頭:

WebClient client = new WebClient(); 
HtmlPage page = client.getPage("http://www.example.com/"); 
WebResponse response = page.getWebResponse(); 

for (NameValuePair header : response.getResponseHeaders()) { 
    System.out.println(header.getName() + " : " + header.getValue()); 
}