Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch HTTP error by java.net.URL

Tags:

java

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

1 Answers

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
}
like image 79
isnot2bad Avatar answered Jan 03 '26 14:01

isnot2bad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!