劉建偉
劉建偉

Reputation: 11

Android WebView set custom header

I'm already override shouldInterceptRequest(final WebView view, final WebResourceRequest request).When I got request from loadUrl,I want to add custom headers.what can I do to fix my code?

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

Upvotes: 0

Views: 1819

Answers (1)

IamVariable
IamVariable

Reputation: 446

Yes, you can add headers when you are using webview, please follow the bellow code. It may help you out.

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

Upvotes: 0

Related Questions