自动 Cookie 处理 C#/.NET HttpWebRequest+HttpWebResponse [英] Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse
问题描述
有没有办法在 .NET 中使用 HttpWebRequest/HttpWebResponse 对象自动处理 cookie?我最好只在 .NET 环境中寻找与 LWP::UserAgent 及其行为 (perl) 等效的东西.
Is there any way to automatically handle cookies in .NET with the HttpWebRequest/HttpWebResponse objects? I'm preferably looking for an equivalent to LWP::UserAgent and its behaviour (perl), only in a .NET environment.
有什么建议或建议吗?
推荐答案
我认为您正在寻找的是 CookieContainer 类.如果我理解您要正确执行的操作,则您有单独的请求对象和对象.响应,并且您希望将 response cookie 集合自动传输到下一个 request cookie 集合中.尝试使用此代码:
I think what you're looking for is the CookieContainer class. If I understand what you're trying to do correctly, you have separate objects for request & response, and you want to transfer the response cookie collection into the next request cookie collection automatically. Try using this code:
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
并将其设置为请求的 CookieContainer,它将存储来自响应的所有 cookie,因此在上面的示例中,cookie jar 的计数将为 1
一旦它访问了 Google.com.请求 & 的 cookie 容器属性上面的响应将存储一个指向 cookieJar 的指针,因此 cookie 会被自动处理并在对象之间共享.
Once you create a cookieJar
and set it to the request's CookieContainer, it will store any cookies that come from the response, so in the example above, the cookie jar's count will be 1
once it visits Google.com. The cookie container properties of the request & response above will store a pointer to the cookieJar, so the cookies are automatically handled and shared between the objects.
这篇关于自动 Cookie 处理 C#/.NET HttpWebRequest+HttpWebResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!