我的函数拦截对 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/gif
、image/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/