I was using the java.net.URL.openStream()
method to retrieve content from the server. I recently ran into an issue where the HTTP Response code indicated an error, but instead of throwing an exception, the stream still was read anyway. This caused the error to appear much later in the execution and proved to be a red herring. As far as I can see, when you have opened a stream using this method, there is no way to check the HTTP response code.
The only way I could find to handle this properly was to obtain a connection before opening the stream:
HttpURLConnection conn=(HttpURLConnection) url.openConnection()
#Code updated with scotth's suggestion
if(!String.valueOf(conn.getResponseCode()).startsWith('2'))
throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage());
rawIn=conn.getInputStream()
InputStream in=conn.getInputStream()
So do you agree? Are there any good circumstances for using openStream safely, or should its use be discouraged. It is worth noting that Sun uses the method in their tutorial code for reading directly from a URL. Then again, the code throws Exception so it isn't exactly a bastion of good coding practices.
openStream()
works just fine if you want your class to be shielded from changes in the type of url - to change between, for example, absolute file paths (file:///), jar-contained resources, and potentially other protocols maybe even with custom protocol handlers (scotth://foo.bar).However, as you've found its abstraction is quite high, so if you desire to know any details whatsoever about the nature of the interaction with the resource you'll need to
openConnection()
and cast as you see fit.Re: other status codes - you probably want to glance at RFC2616 - if all you care about is "successful" you can just check that
String.valueOf(conn.getResponseCode()).startsWith('2')
.