java - 将 .gif 或 .png 图像 WebResourceResponse 应答至 shouldInterceptRequest

标签 java android webview png gif

我的函数拦截对 webview 所做的所有请求。就像加载页面一样。

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

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

不得不说,我想要发送的图像是通过InputStream中的HttpURLConnection接收的,并转换为String,并保存在一个文件夹;因此,当我需要图像时,我只需获取该文件(String)并将其转换为 InputStream

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

我尝试使用 image/gifimage/png 但没有任何效果。

有什么想法吗?

最佳答案

输出流需要是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
}

关于java - 将 .gif 或 .png 图像 WebResourceResponse 应答至 shouldInterceptRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23436667/

相关文章:

java - 无法从 JNI 调用回调函数

Android 联系人选择器已过滤

xcode - 在 WebView 中显示 HTML 代码

java - 为什么 getPreferredSize() 返回的大小对于此 JDialog 来说太小?

java - 使用 RESTTemplate spring boot 使用公共(public) REST API

java - 在 Java 中重新保存 Blob 文件

java - 为什么在 Java 1.8 中使用 Function<V,R> 而不是 Function<R,V>?

Android ListView展开项目列表

iphone - Pinterest 在 iOS 应用程序中的集成?

android - 使浏览器 cookie 在 web View 中可用