url.openStream有害吗? [英] Is url.openStream harmful?

查看:634
本文介绍了url.openStream有害吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 java.net.URL.openStream()方法从服务器检索内容。我最近遇到了一个问题,其中HTTP响应代码指示错误,但不是抛出异常,仍然仍然读取流。这导致错误出现在执行的后期,并被证明是一个红鲱鱼。据我所知,当您使用此方法打开流时,无法检查HTTP响应代码。

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()

所以你同意吗?安全使用openStream是否有任何好的情况,或者不鼓励使用它。值得注意的是,Sun在其教程代码中使用了该方法。直接从网址阅读。然后,代码抛出Exception,因此它不是良好编码实践的堡垒。

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()可以正常工作,如果你希望你的类不受url类型变化的影响 - 例如,在绝对文件路径(file:///),jar-之间进行更改包含资源,可能还有其他协议甚至可能使用自定义协议处理程序(scotth://foo.bar)。

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).

然而,正如您发现它的抽象相当高,所以如果你想知道关于与资源交互性质的任何细节,你需要 openConnection()并按你认为合适的方式进行投射。

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:其他状态代码 - 你可能想看一眼 RFC2616 - 如果你关心的只是成功,你可以检查 String.valueOf(conn.getResponseCode())。startsWith('2')

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').

这篇关于url.openStream有害吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆