In Java read the status code of an HTTP request?

If you use the URL.openStream() method, there's no way to determine whether a request was successful or not. The only alternative is to use the URL.openConnection() method, which returns a URLConnection instance. The URLConnection is an abstract class, meaning that it provides a template of methods, which other classes will implement. Even though the URL.openConnection() method returns a URLConnection instance, it is actually returning a concrete implementation of that class.

When a request is made for a resource using the Hypertext Transfer Protocol, the implementation of URLConnection that is returned is a This class defines additional methods, one of that allows you to access the response status code. To find out the status of a request, you need to cast the URLConnection to a HttpURLConnection, and invoke the int HttpUrlConnection.getResponseCode() method.

URL url = new URL ( some_url );
URLConnection connection = url.openConnection();
// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
   HttpURLConnection httpConnection = (HttpURLConnection) connection;
   int code = httpConnection.getResponseCode();
   // do something with code .....
   System.err.println ("error - not a http request!");

Added on August 28, 2008 Comment