我正在编写一个Android应用程序,它使用webview从Web服务器请求内容,但是使用mWebView.loadUrl(url1,headers);只会将标头应用于初始请求,而不是请求中的资源。
任何想法如何将标头应用于资源请求?
答案 0 :(得分:0)
不完全确定,但您可以尝试覆盖shouldOverrideUrlLoading(WebView view, String url)
方法,并通过启动mWebView.loadUrl(url, yourHeaders);
来处理所有重定向
别忘了在覆盖方法中返回true。
答案 1 :(得分:0)
首先,请允许我说,我无法相信webview太糟糕了。
这就是我传递自定义标题的方法
public class CustomWebview extends WebView {
public void loadWithHeaders(String url) {
setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//makes a custom http request, which allows you to add your own headers
return customRequest(url);
}
});
loadUrl(url);
}
/**
* Custom http request with headers
* @param url
* @return
*/
private WebResourceResponse customRequest(String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url.trim())
.addHeader("Header-Name", "Android Sucks")
.build();
Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
"text/html", // You can set something other as default content-type
"utf-8", // Again, you can set another encoding as default
response.body().byteStream()
);
} catch (IOException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
}
}
}