How to share cookie between HttpWebRequest and WebView

December 13, 2013 by Anuraj

.Net .Net 3.0 / 3.5 Xamarin

This is post is about another hybrid application scenario. I had to implement this in one of our projects, the problem was like this, unlike other hybrid applications, this project had a native login screen, which will authenticate the user against a REST API service and once the authentication is successful, service will set an authentication cookie. And once authentication is completed, application will start a new activity, which will load the web application. If cookie is not present, the web application will show the Forms authentication screen.

Here is the implementation.

For accessing cookie from HttpWebRequest class, you need to create a CookieContainer class, and need to set CookieContainer property of HttpWebRequest.

var cookieContainer = new CookieContainer ();
var httpWebRequest = WebRequest.Create(_authUrl) as HttpWebRequest;
httpWebRequest.CookieContainer = cookieContainer;

After receiving the response from HttpWebRequest, you can access the cookies via HttpWebResponse.Cookies property.

var cookies = httpWebResponse.Cookies;

You can set the cookie for WebView by getting the cookie manager instance and invoking SetCookie() method.

var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie (true);
cookieManager.SetCookie (cookie_domain, cookie_name + "=" + cookie_value);
webView.SetWebViewClient (new CustomWebViewClient ());
webView.LoadUrl (url);

Here is CustomWebViewClient implementation.

private class CustomWebViewClient : WebViewClient
{
	public override bool ShouldOverrideUrlLoading (WebView view, string url)
	{
		view.LoadUrl (url);
		return true;
	}
}

Happy Programming :)

You can find the source code on github – https://github.com/anuraj/CookieSharing

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub