locked
How to save cookies in HttpClient?

    Question

  • Hello. How can I save cookies with HttpClient?

    With WebClients I used this:

    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Net;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace ConsoleApplication1
    {
    	public class WebClientEx : WebClient
    	{
    		public WebClientEx()
    		{
    			this.container = ReadCookiesFromDisk(cookiefile);
    		}
    
    		public CookieContainer CookieContainer
    		{
    			get { return container; }
    			set { container = value; }
    		}
    
    		private CookieContainer container = new CookieContainer();
    		private string cookiefile = "cookies.txt";
    
    		protected override WebRequest GetWebRequest(Uri address)
    		{
    			WebRequest r = base.GetWebRequest(address);
    			var request = r as HttpWebRequest;
    			if (request != null)
    			{
    				request.CookieContainer = container;
    			}
    			return r;
    		}
    
    		protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    		{
    			WebResponse response = base.GetWebResponse(request, result);
    			ReadCookies(response);
    			return response;
    		}
    
    		protected override WebResponse GetWebResponse(WebRequest request)
    		{
    			WebResponse response = base.GetWebResponse(request);
    			ReadCookies(response);
    			return response;
    		}
    
    		private void ReadCookies(WebResponse r)
    		{
    			var response = r as HttpWebResponse;
    			if (response != null)
    			{
    				CookieCollection cookies = response.Cookies;
    				container.Add(cookies);
    				WriteCookiesToDisk(cookiefile, container);
    			}
    		}
    
    		public void WriteCookiesToDisk(string file, CookieContainer cookieJar)
    		{
    			using (Stream stream = File.Create(file))
    			{
    				try
    				{
    					Debug.WriteLine("Writing cookies to disk...");
    					BinaryFormatter formatter = new BinaryFormatter();
    					formatter.Serialize(stream, cookieJar);
    					Debug.WriteLine("Done.");
    				}
    				catch (Exception e)
    				{
    					Debug.WriteLine("Problem writing cookies to disk: " + e.GetType());
    				}
    			}
    		}
    
    		public CookieContainer ReadCookiesFromDisk(string file)
    		{
    			try
    			{
    				using (Stream stream = File.Open(file, FileMode.Open))
    				{
    					Debug.WriteLine("Reading cookies from disk...");
    					BinaryFormatter formatter = new BinaryFormatter();
    			
    					Debug.WriteLine("Done.");
    					return (CookieContainer)formatter.Deserialize(stream);
    				}
    			}
    			catch (Exception e)
    			{
    				Debug.WriteLine("Problem reading cookies from disk: " + e.GetType());
    				return new CookieContainer();
    			}
    		}
    	}
    }
    

    So, just after that I have:

    //This is first time we open page -> no cookies -> creating cookie 'test' with value '1'
    var webclient = new WebclientEx();
    var response = webClient.DownloadString("http://mydomain.com?act=viewcookies");
    Debug.WriteLine(response);
    
    //This is second time we open page -> if cookie 'test' exists, just reset value to '2' and if cookie 'test' does not exists, create 'test' with value '1' 
    var webclient2 = new WebClientEx();
    var response2 = webclient2.DownloadString("http://mydomain.com/?act=viewcookies");
    Debug.WriteLine(response2);
    
    //Output
    "We just created cookie 'test' with value '1'."
    "We just reset cookie 'test' ('1') with new value '2'."

    Well, simply, I need this code working with HttpClient instead of WebClient (actually, you can tell me how to use WebClient in Windows Phone 8.1/Windows 8.1 Apps). Any thoughts?
    Idea is to retrieve cookies from the page, just store them (I don't want even to open it), and then, at the second request, just pass this cookies to server.

    I tried this:

    CookieContainer cookies = new CookieContainer();
    
    for(int i = 0; i < 2; i++)
    {
    HttpClientHandler handler = new HttpClientHandler
    			{
    				AllowAutoRedirect = true,
    				UseCookies = true,
    				CookieContainer = cookies
    			};
    var client = new System.Net.Http.HttpClient(handler);
    var response = await client.GetStringAsync(new Uri("http://mysite.com/?act=viewcookies"));
    System.Diagnostics.Debug.WriteLine(response);
    }
    

    ... and I got this:

    //Output with HttpClient
    "We just created cookie 'test' with value '1'."
    "We just created cookie 'test' with value '1'."
    It looks like HttpClient doesn't store cookies in CookieContainer.

    Sunday, April 12, 2015 10:20 PM

All replies

  • try with :

    MessageProperties props = OperationContext.Current.IncomingMessageProperties;

                           

    HttpResponseMessageProperty prop = props[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;

                            sharedCookie = prop.Headers["Set-Cookie"];






    Monday, April 13, 2015 6:08 AM