How to read the status code of a HTTP request?

  Uncategorized

If you open a URLConnection with the Hypertext Transfer Protocol, the Object of URLConnection that is returned from openConnection is a HttpURLConnection. This class defines a method, which is able to access the status code of the http response. To get the status of your http reesponse, it is necessary to cast the URLConnection Object to a HttpURLConnection, and invoke the method getResponseCode().

URL url = new URL ( “http://1br.de/” );
URLConnection connection = url.openConnection();

Int code;
connection.connect();
if ( connection instanceof HttpURLConnection)
{
   HttpURLConnection httpConnection = (HttpURLConnection) connection;
   code = httpConnection.getResponseCode();
}
// In this case the code is 200

Most used codes are:

  • 200 OK
  • 301 Moved Permanently
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 500 Internal Server Error

A list of available HTTP Response codes can be found at http://en.wikipedia.org/wiki/List_of_HTTP_status_codes.