Reading Java Images from a URL

I am trying to get an image from the internet from a url in java. I am using the following code.

URL url = new URL(webAddress);
image = ImageIO.read(url);

Sometimes it works, and sometimes it just hangs endlessly, depending on what WebAddress is. There is no error message, it just works and does nothing.

At the addresses where it is hung, there are always images confirmed by copying and pasting them into a web browser. It seems that there are no templates with which they work, and which - not all - they are all jpeg. I did some searches and found some other ways to get the image from the url, but the same thing happens with all of them: they work with some images and hang on others.

Do you have any idea what could be causing this, and how to fix it?

+5
source share
1 answer

Hmm, I'm not sure if we try this and see if there are any changes or errors. I also think maybe you have setRedirects (boolean b) on false, this can also cause problems, but try 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 an error: http://bugs.sun.com/view_bug.do;jsessionid=2bc7386e2f8b4e2550f8b10122f?bug_id=6309072 to check this if the error still occurs with the code above:

        Image img=new ImageIcon(url).getImage();
+5
source

All Articles