Android WebView设置自定义标头

时间:2018-12-03 07:28:48

标签: android webview

我已经覆盖了shouldInterceptRequest(最终的WebView视图,最终的WebResourceRequest请求)。当我从loadUrl收到请求时,我想添加自定义标头。该怎么办才能修复我的代码?

@SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, final WebResourceRequest request) {
            if (request != null && request.getUrl() != null) {
                String scheme = request.getUrl().getScheme().trim();
                if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) {
                    WiFiSingleton wiFiSingleton = new WiFiSingleton ();
                    request.getRequestHeaders().put("token", wiFiSingleton.getToken());
                    return super.shouldInterceptRequest(view, request);
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

1 个答案:

答案 0 :(得分:0)

是的,您可以在使用webview时添加标题,请遵循以下代码。可能会对您有所帮助。

protected void postURL(final String url, String postData) {
    Request request = new Request.Builder()
        .url(url)
        .addHeader("Cache-Control", "max-age=0")
        .addHeader("Origin", "null") //Optional
        .addHeader("Upgrade-Insecure-Requests", "1")
        .addHeader("User-Agent", webView.getSettings().getUserAgentString())
        .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
        .addHeader("Accept-Language", Locale.getDefault().getLanguage())
        .addHeader("Cookie", CookieManager.getInstance().getCookie(url))
        .addHeader("X-Requested-With", BuildConfig.APPLICATION_ID)
        .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), postData))
        .build();

    new OkHttpClient().newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
          Timber.e(e.getMessage());
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        final String htmlString = response.body().string();

        webView.post(new Runnable() {
            @Override
            public void run() {
                webView.clearCache(true);
                webView.loadDataWithBaseURL(url, htmlString, "text/html", "utf-8", null);
            }
        });
    }
});
}