I'm trying to get an image off the internet from an URL in java. I'm using the following code.
URL url = new URL(webAddress);
image = ImageIO.read(url);
Sometimes it works and sometimes it just hangs indefinitely, depending on what WebAddress is. No error message, it just keeps running and doing nothing.
There are definitely images at the addresses where it hangs forever, as confirmed by copying and pasting them into a web browser. There appears to be no pattern to which ones work and which ones don't- they're all jpegs. I've done some searching and found some other methods for getting an image from an URL, but the same thing happens with all of them- they work on some images and hang on others.
Do you have any idea what could be causing this, and how to fix it?
Hmm I'm not sure try this and see if any change or error is thrown. I also think maybe you have setRedirects(boolean b) to false this also maybe giving problems but try this first:
URLConnection con = null;
InputStream in = null;
try {
String webadd="urls go here try the two you have had probelms with and success";
URL url = new URL(webadd);
con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
in = con.getInputStream();
Image img = ImageIO.read(in);
if (img != null) {
System.out.println("Loaded");
} else {
System.out.println("Could not load");
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(is != null) {
try {
is.close();
} catch(IOException ex) {
// handle close failure
}
}
if(con != null) {
con.disconnect();
}
}
}
EDIT: or maybe a bug?: http://bugs.sun.com/view_bug.do;jsessionid=2bc7386e2f8b4e2550f8b10122f?bug_id=6309072 to check this if the error still occurs with the above code try:
Image img=new ImageIcon(url).getImage();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With