Is url.openStream harmful?

Posted by Casebash on Stack Overflow See other posts from Stack Overflow or by Casebash
Published on 2010-06-07T02:24:52Z Indexed on 2010/06/07 2:32 UTC
Read the original article Hit count: 249

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about best-practices