使用HttpClient获取URL状态的最快方法是什么?我不想下载页面/文件,我只是想知道页面/文件是否存在?(如果它是重定向,我希望它遵循重定向)
答案 0 :(得分:12)
以下是我从HttpClient获取状态代码的方法,我非常喜欢:
public boolean exists(){
CloseableHttpResponse response = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpHead headReq = new HttpHead(this.uri);
response = client.execute(headReq);
StatusLine sl = response.getStatusLine();
switch (sl.getStatusCode()) {
case 404: return false;
default: return true;
}
} catch (Exception e) {
log.error("Error in HttpGroovySourse : "+e.getMessage(), e );
} finally {
try {
response.close();
} catch (Exception e) {
log.error("Error in HttpGroovySourse : "+e.getMessage(), e );
}
}
return false;
}
答案 1 :(得分:6)
使用HEAD来电。它基本上是一个GET调用,服务器不返回正文。他们的文档示例:
HeadMethod head = new HeadMethod("http://jakarta.apache.org");
// execute the method and handle any error responses.
...
// Retrieve all the headers.
Header[] headers = head.getResponseHeaders();
// Retrieve just the last modified header value.
String lastModified = head.getResponseHeader("last-modified").getValue();
答案 2 :(得分:0)
您可以使用:
HeadMethod head = new HeadMethod("http://www.myfootestsite.com");
head.setFollowRedirects(true);
// Header stuff
Header[] headers = head.getResponseHeaders();
确保您的Web服务器支持HEAD命令。
中的第9.4节答案 3 :(得分:0)
您可以使用java.net.HttpURLConnection
获取此信息:
URL url = new URL("http://stackoverflow.com/");
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection) {
int responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
// HTTP Status-Code 302: Temporary Redirect.
break;
case HttpURLConnection.HTTP_MOVED_TEMP:
// HTTP Status-Code 302: Temporary Redirect.
break;
case HttpURLConnection.HTTP_NOT_FOUND:
// HTTP Status-Code 404: Not Found.
break;
}
}