7

我正在编写一个使用 webview 从 web 服务器请求内容的 android 应用程序,但使用 mWebView.loadUrl(url1, headers); 只会将标头应用于初始请求,而不是请求中的资源。

关于如何将标头也应用于资源请求的任何想法?

4

2 回答 2

0

不是绝对确定,但您可以尝试覆盖方法并通过启动 不要忘记在该覆盖方法中返回 true 来shouldOverrideUrlLoading(WebView view, String url)处理所有重定向。mWebView.loadUrl(url, yourHeaders);

于 2013-05-08T12:52:43.450 回答
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;
    }
}

}

于 2016-07-15T12:58:12.003 回答