将ImageIO.read与重定向URL一起使用

时间:2011-01-31 14:20:54

标签: java http javax.imageio jai

我正在尝试使用ImageIO从网上读取图像:

URL url = new URL(location);
bi = ImageIO.read(url);

location 是以实际图片结尾的网址(例如http://www.lol.net/1.jpg)时,上述代码有效。但是,当网址是重定向时(例如http://www.lol.net/redirection,导致http://www.lol.net/1.jpg),上面的代码会在 bi 中返回 null

两个问题。一,为什么会发生这种情况?是因为ImageIO库试图根据URL字符串找到合适的ImageReader吗?第二,这个限制最干净的解决方案是什么?请注意,我需要 BufferedImage 输出而不是 Image 输出。

编辑:对于想要测试它的人,我正在尝试阅读的网址为http://graph.facebook.com/804672289/picture,该网址已转换为 http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs351.snc4/41632_804672289_6662_q.jpg

编辑2 :我在上一次编辑中不正确。网址为https://graph.facebook.com/804672289/picture。如果我用http替换https,上面的代码工作正常。所以我的新问题是如何让它与HTTPS一起工作,所以我不需要做替换。

4 个答案:

答案 0 :(得分:4)

对我而言,http://www.lol.net/1.jpg似乎不直接指向图像。

正如@Bozho指出的那样,ImageIO使用默认的URL.openConnection(因为地址以“http”开头)返回HttpURLConnection,默认情况下为setFollowRedirects(true)

关于你的编辑,这段代码似乎对我有用:

URL url = new URL("http://graph.facebook.com/804672289/picture");
BufferedImage bi = ImageIO.read(url);

System.out.println(bi);
// Prints: BufferedImage@43b09468: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@7ddf5a8f transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 50 height = 50 #numDataElements 3 dataOff[0] = 2

我怀疑你的错误是在其他地方。

答案 1 :(得分:4)

我遇到了与https图片链接相同的问题。问题是,当我读取https链接时,在代码中,它将返回200.但实际上它是301.为了解决这个问题,我使用了" curl" user-agent,这样我就可以获得301并迭代直到找到最终的链接。请参阅以下代码:

希望这有助于@Eldad-Mor。

private InputStream getInputStream(String url) throws IOException {
        InputStream stream = null;
        try {
            stream = handleRedirects(url);
            byte[] bytes = IOUtils.toByteArray(stream);
            return new ByteArrayInputStream(bytes);
        } finally {
            if (stream != null)
                stream.close();
        }
    }

    /**
     * Handle redirects in the URL Manually. Method calls itself if redirects are found until there re no more redirects.
     * 
     * @param url URL
     * @return input stream
     * @throws IOException
     */
    private InputStream handleRedirects(String url) throws IOException {
        HttpURLConnection.setFollowRedirects(false);
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestProperty("User-Agent", "curl/7.30.0");
        conn.connect();
        boolean redirect = false;
        LOG.info(conn.getURL().toString());

        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }
        if (redirect) {
            String newUrl =conn.getHeaderField("Location");
            conn.getInputStream().close();
            conn.disconnect();
            return handleRedirects(newUrl);
        }
        return conn.getInputStream();
    }

答案 2 :(得分:2)

关于您的编辑2:

ImageIo.read(url),不关心url类型。即,http或https。

您只需将网址传递给此方法即可,但如果您要传递https网址,则需要执行某些步骤来验证SSL证书。请找到以下示例。

1)对于http& HTTPS:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 * @author Syed CBE
 *
 */
public class Main {


    public static void main(String[] args) {

                int height = 0,width = 0;
                String imagePath="https://www.sampledomain.com/sampleimage.jpg";
                System.out.println("URL=="+imagePath);
                InputStream connection;
                try {
                    URL url = new URL(imagePath);  
                    if(imagePath.indexOf("https://")!=-1){
                        final SSLContext sc = SSLContext.getInstance("SSL");
                        sc.init(null, getTrustingManager(), new java.security.SecureRandom());                                 
                        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                        connection = url.openStream();
                     }
                    else{
                        connection = url.openStream();
                    }
                    BufferedImage bufferedimage = ImageIO.read(connection);
                    width          = bufferedimage.getWidth();
                    height         = bufferedimage.getHeight();
                    System.out.println("width="+width);
                    System.out.println("height="+height);
                } catch (MalformedURLException e) {

                    System.out.println("URL is not correct : " + imagePath);
                } catch (IOException e) {

                    System.out.println("IOException Occurred : "+e);
                }
                catch (Exception e) {

                    System.out.println("Exception Occurred  : "+e);
                }


    }

     private static TrustManager[] getTrustingManager() {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                   @Override
                   public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return null;
                   }

                   @Override
                   public void checkClientTrusted(X509Certificate[] certs, String authType) {
                   }

                   @Override
                   public void checkServerTrusted(X509Certificate[] certs, String authType) {
                   }
            } };
            return trustAllCerts;
     }

}

2)仅针对http:

// This Code will work only for http, you can make it work for https but you need additional code to add SSL certificate using keystore
    public static void getImage(String testUrl) {

            String testUrl="https://sampleurl.com/image.jpg";

        HttpGet httpGet = new HttpGet(testUrl);
                 System.out.println("HttpGet is  ---->"+httpGet.getURI());
                HttpResponse httpResponse = null;
                HttpClient httpClient=new DefaultHttpClient();

                try {

                    httpResponse = httpClient.execute(httpGet);
                    InputStream stream=httpResponse.getEntity().getContent();
                     BufferedImage sourceImg = ImageIO.read(stream);
                    System.out.println("------ source -----"+sourceImg.getHeight());
                     sourceImg.getWidth();
                        System.out.println(sourceImg);
                }catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("------ MalformedURLException -----"+e);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                System.out.println("------  IOEXCEPTION -----"+e);
                }
    }

答案 3 :(得分:0)

目前可以使用Apache HttpClient,对我来说它运行正常。

http://hc.apache.org/

    public static void main(String args[]) throws Exception{
    String url = "http://graph.facebook.com/804672289/picture?width=800";

    HttpClient client = HttpClients.createDefault();
    HttpResponse response = client.execute(new HttpGet(url));
    BufferedImage image = ImageIO.read(input);

    if(image == null){
        throw new RuntimeException("Ooops");
    } else{
        System.out.println(image.getHeight());
    }
}