如何通过java.net.URL捕获HTTP错误

3

我有一小段代码片段,其中我打开了一个带有一些图片的filer的URLStream。

如果我可以从运行代码的目标位置访问这个filer,那么代码就能正常工作。但是如果我在没有访问该filer的权限的位置运行代码,代码将无法工作。但是,代码中没有任何错误!代码可以正常工作,并在找不到图像时抛出自定义异常。

那么我如何捕获任何(或只是401)HTTP错误呢?请注意,我知道如何授权调用,但我不想这样做。我只想处理HTTP错误。

以下是我的代码片段:

(...)
URL url = new URL("http://filer.example.com/pictures/" + list.get(0) + ".jpg"); 
IputStream in = new BufferedInputStream(url.openStream());
(...)
1个回答

5
您现在的做法是使用缩写形式,与较长的形式相比。
URL url = new URL("http://filer.example.com/pictures/" + list.get(0) + ".jpg");
URLConnection connection = url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();

在HTTP协议中,您可以安全地将URLConnection转换为HttpURLConnection以访问与协议相关的内容:

URL url = new URL("http://filer.example.com/pictures/" + list.get(0) + ".jpg");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    // everything ok
    InputStream in = connection.getInputStream();
    // process stream
} else {
    // possibly error
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接