我使用此答案提供的代码下载网站并与之互动。
https://stackoverflow.com/a/1031335/1689144
// establish the client and base
CookieAwareWebClient client = new CookieAwareWebClient();
client.BaseAddress = @"some_url";
// establish login data
var loginData = new NameValueCollection();
loginData.Add("username", Settings.Default.username.ToLower());
loginData.Add("password", Settings.Default.password);
// begin login
client.UploadValues("/login", "POST", loginData);
我遇到麻烦的地方。我认为CookieContainer
是NameValueCollection
。它不是......我如何阅读CookieContainer
的内容?
//NOM NOM NOM cookies
var nomNomCookies = client.CookieContainer;
foreach (var cookie in nomNomCookies)
{
//test
Console.WriteLine(cookie.Name + " " + cookie.Value);
}
答案 0 :(得分:1)
如果你想使用这个hacky解决方案:
public static IEnumerable<Cookie> GetAllCookies(CookieContainer cookieContainer)
{
var domainTable = (Hashtable)cookieContainer
.GetType()
.InvokeMember(
name: "m_domainTable",
invokeAttr: BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance,
binder: null,
target: cookieContainer,
args: new object[] { });
return domainTable.Keys.Cast<string>()
.Select(d => cookieContainer.GetCookies(new Uri("http://" + d.TrimStart('.'))))
.SelectMany(c => c.Cast<Cookie>());
}