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

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

问题描述

有没有什么办法可以在.NET自动处理cookie与HttpWebRequest的/ HttpWebResponse对象?我是preferably寻找一个相当于LWP ::用户代理和其行为(perl的),只能在.NET环境。

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 类。如果我理解你想要正确地做什么,你有要求和功放独立的对象;响应,并且要转让的响应的Cookie集合到下的请求的Cookie集合自动。尝试使用这种code:

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,所以在上面的例子中,饼干罐的数量将 1 一旦访问Google.com。请求与放大器的饼干容器属性;上述响应将存储一个指向cookieJar,所以饼干自动处理和共享对象之间

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天全站免登陆