C# - Cookie Management
I asked a question on here earlier and got some fantastic responses. I've since been diddling Visual C# and ran into a bit of a problem.
Here I made a simple page that sets a cookie.
If you go to it and then refresh, it'll see if there's a cookie present and change the output html.
Now, I want my C# program to fetch a page, get a cookie and then re-visit the page again with the cookie that is set, so that my page presents me the "updated" message. I accomplished phase one via:
private void button1_Click(object sender, RoutedEventArgs e)
{
WebRequest request = WebRequest.Create("http://www.binarywatch.biz/forms/cookietest.php");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
MessageBox.Show(responseFromServer, "Derp");
reader.Close();
dataStream.Close();
response.Close();
}
So at this point I have the page html but I'm a bit lost as to how to go about getting a cookie (Something to do with CookieContainer() ? ) and then m开发者_如何学编程aking the page know that I have it (by adding it to the httpwebrequest somehow?)
I tried googling it of course but a LOT of the answers I find are about ASP.NET / web programming and that's not what I need.
PS. What's the difference between WebRequest and HttpWebRequest?
I hope this isn't too noobish, I'm a bit stumped.
according to MSDN you'd first create an instance of the CookieContainer before calling getResponse. After that you should be able to get cookie data out of the CookieContainer you created.
(request as HttpWebRequest).CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
CookieCollection cookies = (request as HttpWebRequest).CookieContainer.GetCookies("www.binarywatch.biz");
string myValue cookies["myCookie"].Value
You should be able to re-use the same CookieContainer object to make sure the server keeps getting access to the cookies.
The GetCookies(domain) is needed as a single CookieContainer is able to store separate cookies safely for multiple domains.
Taken from "how to use cookies in httpwebrequest?"
Yes, use CookieContainer.
CookieContainer cookieContainer = new CookieContainer();
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
httpWebRequest.CookieContainer = cookieContainer;
From that answer:
"After the GetResponse call the cookieContainer will contain the cookies sent back from the requested Url."
I haven't tested this, but it was the accepted answer so it must work. Hope it works for you.
精彩评论