How to read the status code of a HTTP request?

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().

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.