如何获取 CookieContainer 内的 cookie 信息?(所有这些,不针对特定领域) [英] How to get cookies info inside of a CookieContainer? (All Of Them, Not For A Specific Domain)
本文介绍了如何获取 CookieContainer 内的 cookie 信息?(所有这些,不针对特定领域)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请看下面的代码:
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
int cookieCount = cookieJar.Count;
如何在 cookieJar
中获取 cookie 信息?(所有这些,而不仅仅是针对特定域.)
以及如何从中添加或删除 cookie?
How can I get cookies info inside cookieJar
? (All of them, not just for a specific domain.)
And how can I add or remove a cookie from that?
推荐答案
reflection 可用于获取保存 CookieContainer 对象中所有域键的私有字段,
reflection can be used to get the private field that holds all the domain key in CookieContainer object,
问.我如何获得该私有字段的名称?
答.使用反射器;
它被声明为:
private Hashtable m_domainTable;
一旦我们获得了私有字段,我们就会获得域密钥,然后获得 cookie 就是一个简单的迭代.
once we get the private field, we will get the the domain key, then getting cookies is a simple iteration.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Net;
using System.Collections;
namespace ConsoleApplication4
{
static class Program
{
private static void Main()
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Cookie("name1", "value1", "/", "domain1.com"));
cookies.Add(new Cookie("name2", "value2", "/", "domain2.com"));
Hashtable table = (Hashtable)cookies.GetType().InvokeMember(
"m_domainTable",
BindingFlags.NonPublic |
BindingFlags.GetField |
BindingFlags.Instance,
null,
cookies,
new object[]{}
);
foreach (var key in table.Keys)
{
Uri uri = new Uri(string.Format("http://{0}/", key));
foreach (Cookie cookie in cookies.GetCookies(uri))
{
Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}",
cookie.Name, cookie.Value, cookie.Domain);
}
}
Console.Read();
}
}
}
这篇关于如何获取 CookieContainer 内的 cookie 信息?(所有这些,不针对特定领域)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文