gpt4 book ai didi

java - 回答 .gif 或 .png 图像 WebResourceResponse 到 shouldInterceptRequest

转载 作者:行者123 更新时间:2023-11-30 09:08:38 28 4
gpt4 key购买 nike

我的函数拦截所有对 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com