Reputation:
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());
(...)
Upvotes: 3
Views: 1935
Reputation: 24454
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
}
Upvotes: 5