简体   繁体   English

Android - Webview仅将标头应用于初始请求

[英]Android - Webview only applying headers to initial request

I'm writing an android app that uses webview to request content from a web server, but using mWebView.loadUrl(url1, headers); 我正在编写一个Android应用程序,它使用webview从Web服务器请求内容,但使用mWebView.loadUrl(url1,headers); will only apply the headers to the initial request and not the resources in the request. 只会将标头应用于初始请求,而不是请求中的资源。

Any idea as so how to apply the headers to the resource requests as well? 任何想法如何将标头应用于资源请求?

Not absolutely sure but you can try to override shouldOverrideUrlLoading(WebView view, String url) method and handle all redirects by starting mWebView.loadUrl(url, yourHeaders); 不完全确定,但您可以尝试覆盖shouldOverrideUrlLoading(WebView view, String url)方法并通过启动mWebView.loadUrl(url, yourHeaders);处理所有重定向mWebView.loadUrl(url, yourHeaders); Dont forget to return true in that overriden method. 别忘了在覆盖方法中返回true。

First of all, let me say that i can't believe that webview sucks so much. 首先,让我说我无法相信webview太糟糕了。

This is what i did to pass custom headers 这就是我传递自定义标头的方法

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;
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM