Where in my C# code do I need to put the code for setting cookies? Firefox shows three cookies when I’m logged in to the system.
Login page
system.local/interface/Login.php
POST /interface/Login.php HTTP/1.1
Host: system.local
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://system.local/interface/Login.php
Cookie: language=en_US.UTF-8; StationID=06ae3ed4d72a33dd951572df84a13725
Content-Type: application/x-www-form-urlencoded
Content-Length: 71
user_name=user&password=password123456&language=en&action%3Asubmit=Submit
GET response from index.php when logged in
http://system.local/interface/index.php
GET /interface/index.php HTTP/1.1
Host: system.local
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: system.local/interface/Login.php
Cookie: language=en_US.UTF-8; StationID=06ae3ed4d72a33dd951572df84a13725; SessionID=3783a8fea972fb99779f7dd3078ed53c
Where to put the cookie(s) in this code?
string url;
string cookieHeader;
string formparam;
HttpWebRequest request;
HttpWebResponse response;
byte[] bytes;
url = "http://system.local/interface/Login.php";
formparam = string.Format("user_name=" + textBox1.Text + "&password=" + textBox2.Text + "&language=en&action%3Asubmit=Submit");
request = (HttpWebRequest)HttpWebRequest.Create(url);
var cookies = new CookieContainer();
request.ContentType = "Content-Type: application/x-www-form-urlencoded";
request.Method = "POST";
bytes = Encoding.ASCII.GetBytes(formparam);
request.ContentLength = bytes.Length;
request.KeepAlive = true;
using (Stream os = request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
response = (HttpWebResponse)request.GetResponse();
cookieHeader = response.Headers["Set-Cookie"];
request = (HttpWebRequest)WebRequest.Create("http://system.local/interface/Login.php");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(response.Cookies);
request.Headers.Add("Cookie", cookieHeader);
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
//richTextBox1.Text = reader.ReadToEnd().Trim();
}
Set the
CookieContainerfield on everyrequest, and it should automatically add the cookies from the header. Use the sameCookieContainerinstance every time and it will maintain its state across multiple requests. You don’t need to mess withCookieorset-cookieheader values, because theCookieContainerhandles that automatically if it’s assigned to the request cookie container.