Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

WebView Custom HTTP Header

$
0
0

I'm trying to append a custom HTTP header to all requests coming from a WebView in a Xamarin Android project. I am able to append headers to the initial request, but future requests from the webview (loading of CSS files, images, etc) do not contain the header. From this StackOverflow post I'm not sure if it's possible.

I have created a WebViewClient to try and override some methods to manually set the header. The OnLoadResource method is called when these resources are loaded, but I don't see a way to set the header. Here's my source:

public class WebViewFragment : Fragment
{
    private string url;
    private WebView webView;

    public WebViewFragment (string url)
    {
        this.url = url;
    }

    public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        LinearLayout layout = new LinearLayout (this.Activity);

        if (null != webView) {
            webView.Destroy ();
        }
        webView = new WebView (container.Context);
        webView.SetWebViewClient (new MyWebViewClient (this.Activity));
        webView.Settings.JavaScriptEnabled = true;
        Dictionary<string, string> headers = new Dictionary<string, string> ();
        headers.Add ("CustomHeaderName", "CustomHeaderValue");
        webView.LoadUrl (url, headers);

        layout.AddView (webView);

        return layout;
    }

    private class MyWebViewClient : WebViewClient {
        private Context context;

        public MyWebViewClient(Context context) {
            this.context = context;
        }

        public override bool ShouldOverrideUrlLoading (WebView view, string url) // called when links in the webview are selected
        {
            Console.WriteLine ("ShouldOverrideUrlLoading: " + url);
            Dictionary<string, string> headers = new Dictionary<string, string> ();
            headers.Add ("CustomHeaderName", "CustomHeaderValue");
            view.LoadUrl (url, headers);
            return true;
        }

        public override void OnLoadResource (WebView view, string url) // called for resources--but can't append header!
        {
            Console.WriteLine ("OnLoadResource: " + url);
            base.OnLoadResource (view, url);
        }
    }
}

Any advice would be appreciated. Thanks!


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>