我正在尝试在帖子请求中保存Cookie。这是我的代码:
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.UserAgent = userAgent;
myHttpWebRequest.CookieContainer = myCookieContainer;
myHttpWebRequest.Method = "POST";
byte[] postdata = encoding.GetBytes(submitString);
myHttpWebRequest.BeginGetRequestStream(async1 =>
{
using (Stream stream = myHttpWebRequest.EndGetRequestStream(async1))
stream.Write(postdata, 0, postdata.Length);
myHttpWebRequest.BeginGetResponse(async2 =>
{
HttpWebResponse rep = (HttpWebResponse)myHttpWebRequest.EndGetResponse(async2);
CookieCollection cookies = rep.Cookies;
using (Stream stream = rep.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
String content = sr.ReadToEnd();
if (pageDownloadedEventHandler != null)
pageDownloadedEventHandler(content);
}
}, null);
}, null);
Alaways CookieContainer是空的。 如何获取cookie?
答案 0 :(得分:1)
如果服务器将您在rep.Cookies以及myCookieContainer中看到的任何cookie发回给您,您的代码似乎是完美的。
如果您想确保使用Fiddler或Wireshark来分析HTTP网络流量并查找cookie,但如果我是对的,您将无法找到它们。在这种情况下,我的想法是分析网络流量与您的浏览器做同样的请求,也许php / asp.net /其他应用程序决定不设置cookie由于一些丢失的请求标题。