How to detect invalid image URL with JAVA?
- by Cataclysm
I have a method to download image from URL. As like below..
public static byte[] downloadImageFromURL(final String strUrl) {
InputStream in;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
URL url = new URL(strUrl);
in = new BufferedInputStream(url.openStream());
byte[] buf = new byte[2048];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
}
catch (IOException e) {
return null;
}
return out.toByteArray();
}
I have an image url and it is valid. for example.
https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcg
My problem is I don't want to download if image is really not exists.Like ....
https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcgaaaaabbbbdddddddddddddddddddddddddddd
This image shouldn't be download by my method. So , how can I know the giving image URL is not really exists. I don't want to validate my URL (I think that may not my solution ).
So, I googled for that. From this article ...
How to check if a URL exists or returns 404 with Java? and
Java check if file exists on remote server using its url
But this con.getResponseCode() will always return status code "200". This mean my method will also download invalid image urls. So , I output my bufferStream as like...
System.out.println(in.read(buf));
Invalid image URL produces "43". So , I add these lines of codes in my method.
if (in.read(buf) == 43) {
return null;
}
It is ok. But I don't think that will always satisfy. Has another way to get it ? am I right? I would really appreciate any suggestions. This problem may struct my head. Thanks for reading my question.