reading image from URL

2019-08-24 10:28发布

问题:

If I execute the following Groovy code

URL url = new URL('http://glowstick.blisstunes.com/wp-content/plugins/rss-poster/cache/e1ebf_josh-wink.jpg')
ImageIO.read(url)

I get an exception:

javax.imageio.IIOException: Can't get input stream from URL!
    at javax.imageio.ImageIO.read(ImageIO.java:1369)

But if I visit the URL in a browser the image displays. Is it because the HTTP request is being blocked because it doesn't look (from the headers) like it's coming from a browser?

回答1:

Use this:

 Image image = Toolkit.getDefaultToolkit().createImage(url);


回答2:

Use the below code as reference. Do similar thing .

                    URL urlTemp ;
                    urlTemp = new URL( ContentUrl);
                    HttpURLConnection ycGetContent = null;
                    ycGetContent = (HttpURLConnection) urlTemp.openConnection();
                    ycGetContent.setDoOutput(true);
                    ycGetContent.setRequestProperty("Cookie", cooStr);
                    ycGetContent.connect();


                    BufferedInputStream bins =
                            new BufferedInputStream(ycGetContent.getInputStream());

                    FileOutputStream fout =
                            new FileOutputStream(lastWord);
                    int m = 0;

                    byte[] bytesIn = new byte[1024];



                    while ((m = bins.read(bytesIn)) != -1) {
                        fout.write(bytesIn, 0, m);
                    }
                    fout.close();
                    bins.close();

                    //System.out.println("File " +lastWord +" downloaded successfully ...\n\n ");   
                    LOG.info("File " +lastWord +" downloaded successfully");


标签: java http groovy