简体   繁体   中英

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

What is the fastest method of getting a URLs status using HttpClient? I don't want to download the page/file, I just want to know if the page/file exists?(If it's a redirect I want it to follow the redirect)

Here is how I get status code from HttpClient, which I like very much:

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;
}

Use the HEAD call. It's basically a GET call where the server does not return a body. Example from their documentation:

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

You can use:

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

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

Do make sure that your web server supports the HEAD command.

See Section 9.4 in the HTTP 1.1 Spec

You can get this Info with 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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