从URL

2012-07-31 36 views
0

读取图像。如果我执行下面的Groovy代码从URL

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

我得到一个异常:

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

但是,如果我访问的URL在浏览器中的图像显示。这是否是因为HTTP请求被阻止,因为它看起来不像(来自头部),就像它来自浏览器?

+0

http://stackoverflow.com/questions/3787966/javax-imageio-iioexception-cant-get-input-stream-from-url应该是同样的问题 – 2012-07-31 14:40:36

+0

该代码工作对我来说在Groovy的控制台...: -/ – 2012-07-31 14:42:14

+0

@tim_yates它也适用于Groovy控制台。它也适用于我在开发环境中运行应用程序。但它在生产中的应用程序的Grails控制台中不起作用。我怀疑龙是责怪。奇怪的是,下面的“工具包”建议确实有效。 – 2012-07-31 14:49:11

回答

2

使用此:

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

这似乎工作,但不幸的是代码需要一个'RenderedImage'而不是'Image'。我检查过这个'image'的实现类型,它不是'RenderedImage'。 – 2012-07-31 15:09:13

+0

你可以将它转换为'BufferedImage'! – elias 2012-07-31 15:52:14

0

使用下面的代码作为参考。做类似的事情。

    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");