【问题标题】:Answer .gif or .png image WebResourceResponse to shouldInterceptRequest将 .gif 或 .png 图像 WebResourceResponse 应答到 shouldInterceptRequest
【发布时间】:2014-06-19 15:23:30
【问题描述】:

我的函数拦截了对 webview 的所有请求。比如加载一个页面。

@Override
public WebResourceResponse shouldInterceptRequest(final WebView view,
    String url) {...}

所有 html、css 和 js 文件都已正确回答,但是当我想发送 png 或 gif 图像作为响应时,它不起作用。他们可能需要特殊的 MIME 类型,但我无法使其工作。

不得不说,我要发送的图片是用HttpURLConnectionInputStream中接收并转换为String,并保存在一个文件夹中;所以当我需要图像时,我只需将该文件(String)转换为InputStream

InputStream is = new ByteArrayInputStream(imageString.getBytes());
return new WebResourceResponse("text/html", "UTF-8", is);

我尝试了image/gifimage/png,但没有任何效果。

有什么想法吗?

【问题讨论】:

  • 如果是发送图片,为什么要将响应内容设置为"text/html"?图像不是 html 也不是文本。在最坏的情况下,使用"application/octet-stream",就好像它是一个通用的下载文件。
  • WebResourceResponse("image/png", "binary", is); 应该适用于 PNG 图像,无需任何转换(例如某些帖子中建议的 base64)。

标签: java android webview png gif


【解决方案1】:

输出流需要是FileOutputStream

图片需保存为字节格式,无需编码。

请记住,您需要保留图像文件扩展名。 例如,如果您正在下载 image.png 并将其保存为 image.tiff,它将无法正常工作。

这就是我下载图像的方式:

URLConnection conn;

BufferedInputStream bistream = null;
BufferedOutputStream bostream = null;

boolean failed = false;

try
{
    conn = new URL("http://../image.png").openConnection();

    bistream = new BufferedInputStream(conn.getInputStream(), 512);

    byte[] b = new byte[512];

    int len = -1;

    bostream = 
        new BufferedOutputStream(
            new FileOutputStream(new File("/../image-downloaded.png")));

    while((len = bistream.read(b)) != -1)
    {
        bostream.write(b, 0, len);
    }
}
catch(Exception e) // poor practice, catch each exception separately.
{                   /* MalformedURLException -> IOException -> Exception */
    e.printStackTrace();

    failed = true;
}
finally
{
    if(bostream != null)
    {
        try
        {
            bostream.flush();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bostream.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    if(bistream != null)
    {
        try
        {
            bistream.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

if(failed == false)
{
    //code
}
else
{
    // code
}

【讨论】:

  • 你的答案让我得到了正确的答案:我将图像保存在 base64 字符串中,然后在使用 WebViewResource 将其发送回 webView 之前,我将其设为字节数组,然后输入流并格式化“image/png "
  • 可以在HTML中显示base64,<img src='data:image/jpeg;charset=utf-8;base64,PLACE_BASE64_STRING_HERE'>
  • 我不想显示它,我只是像普通服务器那样回答请求。
猜你喜欢
  • 2015-02-17
  • 1970-01-01
  • 2023-04-04
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
相关资源
最近更新 更多