Check if resource exists
suggest change/**
* Checks if a resource exists by sending a HEAD-Request.
* @param url The url of a resource which has to be checked.
* @return true if the response code is 200 OK.
*/
public static final boolean checkIfResourceExists(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
int code = conn.getResponseCode();
conn.disconnect();
return code == 200;
}
Explanation:
If you are only checking that a resource exists, a HEAD request is better than a GET. It avoids downloading the body.
The method returns true only for status 200. Redirects (3xx) count as absent unless you follow them. The comments below are what those hosts returned when the example was written; they are not a permanent result.
Example:
checkIfResourceExists(new URL("http://images.google.com/")); // true
checkIfResourceExists(new URL("http://pictures.google.com/")); // false
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents