gpt4 book ai didi

android - 无法覆盖 shouldInterceptRequest() 来发出我自己的 HTTP 请求

转载 作者:行者123 更新时间:2023-11-30 03:03:24 27 4
gpt4 key购买 nike

我在 Android (KitKat) 上使用 WevView,我正在尝试覆盖 shouldInterceptRequest() 并发出我自己的 HTTP 请求 - 让我的应用而不是 webview 处理请求。

我的观点是解决 webview 的跨源限制,这可能不是一个好主意,但这是另一个问题。

当我将从我的 HTTP 请求接收的数据传递给 shouldInterceptRequest() 方法返回的 WebResourceResponse 对象时出现问题。在这一点上值得一提的是,这是我的第一个 Android 应用程序(不是从正确的任务开始,但是嘿)而且我对 Android 上的流的了解是有限的。我觉得有一些同步问题,也许 webview 需要缓冲数据而我的 InputStream 没有缓冲?无论如何,尽管在不同的论坛上四处寻找,我还是无法弄清楚问题到底是什么。

我的代码是这样的:

    mWebView.setWebViewClient( new WebViewClient()
{
public WebResourceResponse shouldInterceptRequest(WebView _view, String _url)
{
URL url;
try {
url = new URL(_url);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}

HttpURLConnection urlConnection;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
return null;
}

WebResourceResponse response = null;
try {

response = new WebResourceResponse( urlConnection.getContentType(),
urlConnection.getContentEncoding(),
urlConnection.getInputStream() );
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}

return response;
}
});

当我运行我的测试应用程序时,它崩溃了。 Logcat 给我以下日志:

W/System.err(4527): java.io.IOException: stream closed
W/System.err(4527): at com.android.okhttp.internal.http.AbstractHttpInputStream.checkNotClosed(AbstractHttpInputStream.java:68)
W/System.err(4527): at com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream.available(HttpTransport.java:476)
W/System.err(4527): at dalvik.system.NativeStart.run(Native Method)
A/libc(4527): Fatal signal 6 (SIGABRT) at 0x000011af (code=-6), thread 4551 (example.webtest)
I/chromium(4527): [INFO:async_pixel_transfer_manager_android.cc(56)] Async pixel transfers not supported

我看到有人试图做类似的事情(System Crash When Overriding shouldInterceptRequest in WebViewClient),但我遇到的错误似乎完全不同。

有什么想法吗?

感谢您的帮助!

最佳答案

我遇到了同样的问题。如果你删除了

urlConnection.disconnect();

它有效。所以原因一定是在检索内容之前关闭了连接。但是我不确定为什么会发生这种情况,我的猜测是 WebResourceResponse 对流进行了一些惰性读取。

只有当 WebResourceResponse 自己关闭流时,我的解决方案才是“干净的”,否则连接和流不会关闭并泄漏资源。

关于android - 无法覆盖 shouldInterceptRequest() 来发出我自己的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22204358/

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