3

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

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.