我试图让 HttpClient 按照我想要的方式工作,我简直要发疯了。这一切都超出了我的想象。
我想要做的就是提供一个 URL,该 URL 可以指向网页、.zip 文件、.doc 文件以及最终到达上述任意位置的重定向。然后我就可以将最终状态代码打印到控制台。
有人可以帮我吗?到目前为止,我已经(把所有东西都扔进去之后,代码变成了一团糟):
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy(){
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect=false;
try {
isRedirect = super.isRedirected(request, response, context );
} catch (org.apache.http.ProtocolException e) {
System.out.println("what?");
e.printStackTrace();
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println(responseCode);
if (responseCode == 301 || responseCode == 302) {
System.out.println("redirect");
return true;
}
}
return isRedirect;
}
});
HttpHead test = new HttpHead("http://support.xbox.com/en-US/xbox-live/troubleshoot/game-play");
HttpEntity httpEntity = null;
try {
HttpResponse response = client.execute(test);
System.out.println(response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println(e);
System.out.println("400");
} catch (IOException e) {
System.out.println("404");
System.out.println(e);
}
编辑:
对于此网址:http://support.xbox.com/en-US/xbox-live/troubleshoot/game-play我得到了 404。我本来期望得到 200。
对于http://www.google.com正如预期的那样,我得到了 200 分。
对于http://tinyurl.com/2tx一个tinyurl重定向到google.com我得到一个200。
我不知道如何看待我的结果。我只是希望能够测试链接,从最终用户的角度来看它们是否正常工作或已损坏。
最佳答案
问题在于您发送的是 HEAD 请求而不是 GET 请求,对此 xbox 网站仅返回 404。
使用:
HttpGet test = new HttpGet("http://support.xbox.com/en-US/xbox-live/troubleshoot/game-play");
没有任何重定向的东西对我来说就很好用。
关于java - HttpClient 获取状态代码并按照重定向获取结束页面状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10655496/