FranticCity
FranticCity

Reputation: 1

android webview custom headers not going out on page resource requests

In my android app I am connecting to a secure site where my login credentials are contained in custom headers. I am able to log in successfully because the custom headers are sent with the new page request. Based on my custom header information there is specific page functionality which is enabled for my device. The problem is that when I load resources from the home page after login the custom headers that I specify in the webview.LoadUrl(); are not sent. So the end result is that I can log in but do not receive the special functionality that is associated with my device.

I have tried both of these overrides. shouldOverrideUrlLoading seems to work when changing URL's but shouldInterceptRequest does not seem to get called on resource requests? If it is my implementation does not work?

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            request.getRequestHeaders().putAll(getExtraHeaders());
            return super.shouldInterceptRequest(view, request);
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url, getExtraHeaders());
                return false;

            }

Upvotes: 0

Views: 4599

Answers (2)

kris larson
kris larson

Reputation: 30985

See if this works a little better for you:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.post(new Runnable() {
        @Override
        public void run() {
            view.loadUrl(url, getExtraHeaders());
        }
    });

    // true means: yes, we are overriding the loading of this url
    return true;
}

This additional code is just a suggestion/outline and should not be taken as cut/paste ready code

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    String mimetype;
    String encoding;

    Map<String, String> headers = new HashMap<>();
    headers.putAll(request.getRequestHeaders());
    headers.putAll(getExtraHeaders());

    URL url = request.getUrl().toString();
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    for (String key : headers.keySet()) {
        conn.setRequestProperty(k, headers.get(k));
        // TODO look for the mimetype and encoding header information and set mimetype and encoding
    }

    // return null here if you decide to let the webview load the resource
    return new WebResourceResponse(mimetype, encoding, conn.getInputStream());
}

Upvotes: 1

Niro
Niro

Reputation: 334

Maybe try a different approach, store whatever your need in a cookie for your host using WebKit's CookieManager and use the request's cookie header instead of your custom headers

Upvotes: 0

Related Questions