What is the fastest way to get URL status code using HttpClient

What is the fastest way to get URL status using HttpClient? I don’t want to load the page / file, I just want to know if the page / file exists (if it is a redirect, I want it to follow the redirect)

+7
source share
4 answers

Use the HEAD call. This is basically a GET call, where the server does not return the body. An 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(); 
+6
source

This is how I get the status code from HttpClient, which I really like:

 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; } 
+8
source

You can use:

 HeadMethod head = new HeadMethod("http://www.myfootestsite.com"); head.setFollowRedirects(true); // Header stuff Header[] headers = head.getResponseHeaders(); 

Make sure your web server supports the HEAD command.

See section 9.4 in HTTP 1.1 Spec

0
source

You can get this information using 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; } } 
0
source

All Articles