我正在尝试将OKHTTP用于webview,因为我需要访问响应头。问题是使用此代码,webview显示简单的html而不是渲染它。
有什么想法吗?
class WebViewClientImpl(val webView: WebView): WebViewClient() {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse {
return handleRequestViaOkHttp(url = request.url.toString())
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun handleRequestViaOkHttp(url: String): WebResourceResponse {
try {
val okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient()
val call = okHttpClient.newCall(Request.Builder().url(url).build())
val response = call.execute()
return WebResourceResponse(
response.header("content-type", "text/html"),
response.header("content-encoding", "utf-8"),
response.body().byteStream()
)
} catch (e: Exception) {
return WebResourceResponse(null, null, null)
}
}
}
答案 0 :(得分:0)
我有同样的问题,可以通过不提供任何模仿类型和编码来解决。我无法将其设置为null,因为它崩溃了。
WebViewClient client = new WebViewClient() {
private OkHttpClient okHttp = new OkHttpClient.Builder().build();
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
Request okHttpRequest = new Request.Builder().url(url).build();
try {
Response response = okHttp.newCall(okHttpRequest).execute();
return new WebResourceResponse("","",response.body().byteStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
webView.setWebViewClient(client);