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)
To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.
HTTP Status Code 404 - Not Found This means the file or page that the browser is requesting wasn't found by the server. 404s don't indicate whether the missing page or resource is missing permanently or only temporarily. You can see what this looks like on your site by typing in a URL that doesn't exist.
To set a different HTTP status code from your Servlet, call the following method on the HttpServletResponse object passed in to your server: res. setStatus(nnn); where nnn is a valid HTTP status code.
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 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With