繁体   English   中英

使用HttpClient获取URL状态代码的最快方法是什么

[英]What's the fastest way to get a URLs status code using HttpClient

使用HttpClient获取URL状态的最快方法是什么? 我不想下载页面/文件,我只想知道页面/文件是否存在?(如果是重定向,我希望它遵循重定向)

以下是我从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;
}

使用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();

您可以使用:

HeadMethod head = new HeadMethod("http://www.myfootestsite.com");
head.setFollowRedirects(true);

// Header stuff
Header[] headers = head.getResponseHeaders();

确保您的Web服务器支持HEAD命令。

请参阅HTTP 1.1规范中的第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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM