在 Java 中从网络下载生成的图像

Download generated image from web in Java

我正在尝试使用来自 http://avatars.adorable.io/ in my application. However, when trying to download for instance the following png: http://api.adorable.io/avatars/285/bla.png 的头像,我的 HttpUrlConnection 说它看到的内容长度为 0。

当我在浏览器中 fiddle 时,我想我发现该网站使用一些脚本来生成头像,我认为它可能在客户端。但是,我对此不是很了解,无法轻易找到答案。

是否可以使用以下代码在 Java 应用程序中下载这些头像之一?

private Pixmap syncDownloadPixmapFromURL(URL url) 
{   
    URLConnection conn;
    try 
    {
        conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(true);
        conn.connect();
        int length = conn.getContentLength();
        if(length<=0) 
        {
            System.out.log("content length = 0!");
            return null;
        }
        InputStream is = conn.getInputStream();
        conn.setConnectTimeout(5000);
        DataInputStream dis = new DataInputStream(is);
        byte[] data = new byte[length];
        dis.readFully(data);
        dis.close();
        Pixmap pixmap = new Pixmap(data, 0, data.length);
        return pixmap;
    } 
    catch (MalformedURLException e) 
    {   
        e.printStackTrace();
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }

    return null;
 }

这是因为服务器没有发送内容长度。服务器不强制执行此操作。正如您提到的,他们使用动态创建内容和写入数据的脚本 "on the fly"。他们在写入内容时不知道数据的长度以将其添加为 header.

Connection:keep-alive
Content-Type:image/png
Date:Mon, 30 May 2016 06:12:49 GMT
Expires:Mon Jun 06 2016 06:12:49 GMT+0000 (UTC)
Server:Cowboy
Transfer-Encoding:chunked
Via:1.1 vegur
X-Powered-By:Express

您可以将流假脱机到 ByteArrayOutputStream,然后从中获取字节数组。

或者您可以使用 Apache Commons IO 之类的东西,它有一个方法可以为您处理这个...

byte[] data = IOUtils.toByteArray(conn.getInputStream());

查看其他实现的答案:Convert InputStream to byte array in Java