HttpClient 4.1 并不总是返回主机值
如果运行以下代码,完成后您将看到 URI 的 Host 值为“null”。这是无效的!执行请求后,它应该始终有一个 URI。
我试图在请求页面后从上下文中获取当前页面(以防发生重定向)。
对于造成的混乱,我深表歉意。我提到重定向是因为我认为这有助于更轻松地说明我的问题。下面的代码应该适用于重定向的页面和未重定向的页面。
插入您最喜欢的网站,没关系。最终的解决方案必须适用于任何网站......那些被重定向的网站和那些没有重定向的网站。
我缺少什么?
public static void main(String args[]) throws ClientProtocolException, IOException
{
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpGet httpGet = new HttpGet("http://www.google.com/");
HttpContext context = new BasicHttpContext();
httpclient.execute(httpGet, context);
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
System.out.println("New URI host (why is it null?): " + currentReq.getURI().getHost());
}
If you run the following code, you will see that the URI has a value of "null" for Host upon completion. This is invalid! It should always have a URI after executing a request.
I am trying to get the current page from the context after the page is requested (in case redirects occurred).
I apologize for the confusion. I mentioned the redirect because I thought it would help illustrate my problem more easily. The code below should work for pages that were redirected and those that were not.
Plug in your favorite site, it doesn't matter. The final solution has to work for ANY site... those that were redirected and those that were not.
What am I missing?
public static void main(String args[]) throws ClientProtocolException, IOException
{
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpGet httpGet = new HttpGet("http://www.google.com/");
HttpContext context = new BasicHttpContext();
httpclient.execute(httpGet, context);
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
System.out.println("New URI host (why is it null?): " + currentReq.getURI().getHost());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自文档(http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html)
From the docs (http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html)
安卓代码?
为什么要在 main 中编码?我认为除了JavaSE之外的程序中不应该有main方法。
HttpGet 已经是 HttpUriRequest 对象,为什么不使用它呢?
我不是专家,也许这会有所帮助。
Android codes?
Why code in main? I think there should be not main method in programs other than JavaSE.
HttpGet is already the HttpUriRequest object, why not use it?
I am not quite an expert, maybe this could help.