Check if an image URL points to an actual image. Space in URL in causing issue

132 Views Asked by At

I am checking if a URL points to an actual image with the following code:

URL obj = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
return (responseCode == HttpURLConnection.HTTP_OK)  // success

But if the image URL has a space in it, this function is returning false, while the URL is valid. It does not change space to %20. What changes should i make to it?

2

There are 2 best solutions below

0
Angellic Doll On

How about you replace spaces in imageUrl in regex with replaceAll() method?

0
ControlAltDel On

Two parts to this:

  1. Check that the HTTP.responseCode is a 1XX or a 2XX code. If not, the URL isn't an (accessible) image
  2. Try checking the response header: content-type