【问题标题】:Android - Webview only applying headers to initial requestAndroid - Webview 仅将标头应用于初始请求
【发布时间】:2012-05-25 10:55:39
【问题描述】:

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

知道如何将标头也应用于资源请求吗?

【问题讨论】:

  • +1 @stotherd 你有解决这个问题的办法吗?我也被这个问题困住了,找不到解决办法?
  • 很遗憾没有,我不得不单独单独申请资源,然后没有完成项目。

标签: android webview


【解决方案1】:

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

【讨论】:

  • 你能详细说明一下吗
【解决方案2】:

首先,让我说,我不敢相信 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;
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2013-04-01
    • 2019-11-11
    相关资源
    最近更新 更多