When retrieving data over HTTP, how do I monitor server response codes? For example, if the server I am connecting to redirects (response code 3xx), how can I tell and how do I get the new host name?

Tim Rohaly

The FAQ How do I download files from a URL using HTTP? shows you how to get the data from a URL; to get the headers you need to do a few more things.

HTTP returns its response code in the first header, so if you are just interested in this you can examine the String returned from connection.getHeaderField(0). To find the new location for a redirect you can look at the results of connection.getHeaderField("location").

Note that when you get a connection from a URL where you have specified a protocol of "http" in the URL string, you will actually be returned a subclass of HttpURLConnection. You can therefore also cast the connection to an HttpURLConnection and use the getResponseCode() method directly. HttpURLConnection will automatically follow a redirect response unless you disable this feature using setFollowRedirects(false).