Reputation: 1423
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)
Upvotes: 8
Views: 18634
Reputation: 199
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;
}
Upvotes: 15
Reputation: 116
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;
}
}
Upvotes: 1
Reputation: 13097
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();
Upvotes: 6
Reputation: 159784
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
Upvotes: 0