简体   繁体   English

Android WebView自定义标头

[英]Android WebView custom headers

I am currently using this code to add a custom header to android WebView 我目前正在使用此代码向android WebView添加自定义标头

Map<String, String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("example", "header");
webView.loadUrl(url, extraHeader);

Above code is working but only on the main page. 上面的代码工作,但只在主页上。 So if I write this code echo $_SERVER['example'] it prints header . 因此,如果我编写此代码echo $_SERVER['example']则会打印header But there is an iframe in the loaded URL which shows an undefined error when I try the same code. 但是在加载的URL中有一个iframe ,当我尝试相同的代码时,它会显示一个未定义的错误。 Is there any way I can fix this? 有什么办法可以解决这个问题吗?

So what I want to do is add custom header not only to the main loaded URL but also on the iframe of the loaded page. 所以我想要做的是不仅将自定义标头添加到主加载的URL,还添加到加载页面的iframe

This worked for me: 这对我有用:

mWebView.setWebViewClient(new MyWebViewClient(token));

in MyWebViewClient 在MyWebViewClient中

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    try {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url.trim())
                .addHeader("token", mToken) //add headers
                .build();
        Response response = httpClient.newCall(request).execute();
        return new WebResourceResponse(
                getMimeType(url), // set content-type
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );
    }  catch (IOException e) {
        return null;
    }
}

//get mime type by url
public String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        if (extension.equals("js")) {
            return "text/javascript";
        }
        else if (extension.equals("woff")) {
            return "application/font-woff";
        }
        else if (extension.equals("woff2")) {
            return "application/font-woff2";
        }
        else if (extension.equals("ttf")) {
            return "application/x-font-ttf";
        }
        else if (extension.equals("eot")) {
            return "application/vnd.ms-fontobject";
        }
        else if (extension.equals("svg")) {
            return "image/svg+xml";
        }
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

No, that is not possible with Android WebView itself. 不,Android WebView本身无法做到这一点。 You have to work around either in your page code, or in your app's code, or on the server. 您必须在页面代码中,应用程序的代码中或服务器上进行处理。

For fixing this on the page's side, you can use XMLHttpRequest for loading subresources. 要在页面上修复此问题,可以使用XMLHttpRequest来加载子资源。 But for that you will have basically to construct the page on the fly. 但为此你基本上可以动态构建页面。

On the app's side, you can use WebViewClient.shouldInterceptRequest , to intercept all the network requests. 在应用程序方面,您可以使用WebViewClient.shouldInterceptRequest来拦截所有网络请求。 You are not allowed to just modify the provided request, instead, you will need to make a new request yourself, but there you will be able to set any headers you want. 您不能仅修改提供的请求,而是需要自己创建新请求,但您可以设置所需的任何标头。 See this example: Android WebViewClient url redirection (Android URL loading system) 查看此示例: Android WebViewClient URL重定向(Android URL加载系统)

On the server side, you can look into Referer header of subresources, which must contain the url of the page that has requested it. 在服务器端,您可以查看子资源的Referer标头,该标头必须包含已请求它的页面的URL。

您可以将此设置添加到您的Web设置,webview的每个请求都将使用此User-Agent标头。

webview.getSettings().setUserAgentString("user-agent-string");

Just add this piece of code before load URL: 只需在加载URL之前添加这段代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().removeAllCookies(null);
}

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

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