2012-02-03 32 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()); 
}