Is url.openStream harmful?
- by Casebash
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 use code such as:
HttpURLConnection conn=(HttpURLConnection) url.openConnection()
if(conn.getResponseCode()!=HttpStatus.SC_OK)
//Raise Exception;
InputStream in=conn.getInputStream()
So do you agree? Is it possible to use openStream safely, or is it a method that should be avoided at all costs. 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.