Reputation: 77616
I'm trying to use OKHTTP for a webview because I need to access the response headers. The problem is using this code the webview displays plain html instead of rendering it.
Any thoughts?
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)
}
}
}
Upvotes: 4
Views: 7256
Reputation: 3621
I have same problem and solve it by NOT providing any mimetype and encoding. I couldn't set null, because it was crashing with it.
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);
Upvotes: 3