Question

How can I read the status code of a HTTP request?

Answer

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 java.net.HttpURLConnection. This class defines additional methods, one of which allow 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();

connection.connect();

// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
   HttpURLConnection httpConnection = (HttpURLConnection) connection;

   int code = httpConnection.getResponseCode();

   // do something with code .....
}
else
{
   System.err.println ("error - not a http request!");
}


Back