自动Cookie处理C#/ .NET HttpWebRequest + HttpWebResponse [英] Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse

查看:205
本文介绍了自动Cookie处理C#/ .NET HttpWebRequest + HttpWebResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用HttpWebRequest / HttpWebResponse对象自动处理.NET中的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.

有任何建议或建议吗?

Any suggestions or advice?

推荐答案

我认为你要找的是 CookieContainer 类。如果我明白你正在努力做什么,你有单独的对象请求&响应,并且您要将响应 cookie集合自动传输到下一个请求 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访问Google.com,cookie jar的计数将为 1 。请求& cookie的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆