Java 什么';这是使用HttpClient获取URL状态代码的最快方法
使用HttpClient获取URL状态的最快方法是什么?我不想下载页面/文件,我只想知道页面/文件是否存在?(如果是重定向,我希望它遵循重定向)使用调用。它基本上是一个GET调用,服务器不返回主体。他们文档中的示例:Java 什么';这是使用HttpClient获取URL状态代码的最快方法,java,performance,httpclient,http-status-codes,Java,Performance,Httpclient,Http Status Codes,使用HttpClient获取URL状态的最快方法是什么?我不想下载页面/文件,我只想知道页面/文件是否存在?(如果是重定向,我希望它遵循重定向)使用调用。它基本上是一个GET调用,服务器不返回主体。他们文档中的示例: HeadMethod head = new HeadMethod("http://jakarta.apache.org"); // execute the method and handle any error responses. ... // Retrieve all the
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();
您可以使用:
HeadMethod head = new HeadMethod("http://www.myfootestsite.com");
head.setFollowRedirects(true);
// Header stuff
Header[] headers = head.getResponseHeaders();
请确保您的web服务器支持HEAD命令
参见中的第9.4节,您可以通过
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;
}
}
下面是我如何从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;
}
感谢您提供了一个可关闭的HTTPResponse示例。“404”是一个神奇的数字——您可以使用Apache的HttpStatus类开关(sl.getStatusCode()){case HttpStatus.SC_CREATED:return false;default:return true;}