简体   繁体   English

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

[英]How to catch HTTP error by java.net.URL

I've a small code snippet where I open a URLStream of a filer with some pictures on it. 我有一个小代码段,其中打开了带有某些图片的文件管理器的URLStream。

The code works fine if I've access to this filer from the destination where I run the code. 如果我可以从运行代码的目标位置访问此文件管理器,则代码可以正常工作。 But if I run the code where I don't have access to the filer, the code won't work. 但是,如果我在无法访问文件管理器的地方运行代码,则该代码将无法工作。 But I don't get any error in the code! 但是我在代码中没有任何错误! The code works properly and throw a custom exception when no images are found. 该代码正常工作,并且在找不到图像时抛出自定义异常。

So how am I able to catch any (or just the 401) HTTP error? 那么,如何捕获任何(或仅是401)HTTP错误? And please, I know how to authorize the call, but I don't want to do this. 而且,我知道如何授权通话,但是我不想这样做。 I just want to handle the HTTP error. 我只想处理HTTP错误。

Here is my code snip: 这是我的代码片段:

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

The way you're doing it is the shortcut for the longer form: 您这样做的shortcut是较长表格的shortcut

URL url = new URL("http://filer.example.com/pictures/" + list.get(0) + ".jpg");
URLConnection connection = url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();

In case of HTTP, you can safely cast your URLConnection to an HttpURLConnection to get access to protocol related stuff: 如果是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM