I'm having issues with handling cookies when using HttpWebRequest.
I'm making a program to manage my account on a small community website. I am able to make get and post request (successfully logged in, etc), but I can't maintain a session cookie to stay logged in.
My code looks like this :
this.cookies = new CookieCollection();
request = (HttpWebRequest)WebRequest.Create(requestURL);
request.CookieContainer = new CookieContainer();
...
request.CookieContainer.Add(cookies);
ASCIIEncoding encodage = new System.Text.ASCIIEncoding();
byte[] data = encodage.GetBytes(Post);
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "whatever";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Method = "POST";
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.AllowWriteStreamBuffering = true;
request.ContentLength = data.Length;
newStream = request.GetRequestStream();
request.ProtocolVersion = HttpVersion.Version11;
newStream.Write(data, 0, data.Length);
...
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
this.cookies = response.Cookies;
...
response.Cookies is always empty (length: 0) and it shouldn't. Could anyone tell what I'm doing wrong? Why are there no cookies associated with the response? thanks in advance
Just read it from Request.Cookies collection. Only new cookies added on the server side are available in Response.Cookies. Request.Cookies contains all (Request+Response) Cookies.
Considering above it seems like there are no additional cookies added by the server which is why you getting no cookies in the response. Does that make sense ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With