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.
My problem is I don't want to download if image is really not exists.Like ....
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 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.
*UPDATE
I call this download method and save downloaded image in some directory as..
// call method to save image
FileSupport.saveFile(filePath+".JPG", data);
After that I tried to output as...
File file = new File(filePath+".JPG);
System.err.println(file.length());
that may also produces "43" for invalid image urls. I want to know why that return "43" for all of invalid urls. what is "43" ?