Check HTTP Image path if valid
I have a question in Java how can I check if an image http path is valid or existing?
For example:
This image is existing. http://g0.gstatic.com/ig/images/promos/homepage_home.pngBut this one is not. http://sampledomain.com/images/fake.png
I would like to make a logic such that:
If(image is exi开发者_开发问答sting)
- do this
Else
- do others
Thanks
UPDATE: Tried it with this code that I got while googling:
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class TestImage {
public static void main(String[] arg){
Image image = null;
try {
URL url = new URL("http://g0.gstatic.com/ig/images/promos/homepage_home.png");
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("Error");
}
}
}
But I always get an error...I am not sure if this is possible.. Any other thoughts?
Make an Http Head request. If it's an existing path you'll get a response back, otherwise you'll get an error.
This does not check that it is a valid image though, just that the path exists. If you want to check whether the image is valid, I think you have got no choice other than to download it.
You can check if the image exists or not using selenium javascript executor.
Hope this code helps you -
picPath is the Url path you want to validate.
result = (Boolean) ((JavascriptExecutor) driver).executeScript(
"var http = new XMLHttpRequest(); http.open('HEAD',arguments[0], false); http.send();return http.status!=404;", picPath);
精彩评论