开发者

Is url.openStream harmful?

开发者 https://www.devze.com 2023-01-02 17:54 出处:网络
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

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 her开发者_C百科ring. 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').

0

精彩评论

暂无评论...
验证码 换一张
取 消