简体   繁体   中英

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.

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

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:

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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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