使用的CookieContainer与WebClient类 [英] Using CookieContainer with WebClient class
问题描述
我已经previously使用的CookieContainer与HttpWebRequest和HttpWebResponse会议,但现在,我想与一个Web客户端使用。据我了解,没有内置的方法好像有对HttpWebRequests( request.CookieContainer
)。 如何可以我收集的cookie从Web客户端中的CookieContainer?
I've previously used a CookieContainer with HttpWebRequest and HttpWebResponse sessions, but now, I want to use it with a WebClient. As far as I understand, there is no built-in method like there is for HttpWebRequests (request.CookieContainer
). How can I collect cookies from a WebClient in a CookieContainer?
<我一个href=\"http://www.google.com/search?rlz=1C1GGLS_enUS308US308&sourceid=chrome&ie=UTF-8&q=webclient.cookiecontainer\">googled对于这一点,并发现下面的示例:
I googled for this and found the following sample:
public class CookieAwareWebClient : WebClient
{
private readonly CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = m_container;
}
return request;
}
}
这是做到这一点的最好方法是什么?
Is this the best way to do it?
推荐答案
是的。恕我直言,覆盖GetWebRequest()是Web客户端的有限functionalty的最佳解决方案。之前,我知道这个选项,我在HttpWebRequest的层写了很多真的很痛苦code,因为几乎WebClient的,但不完全,做了我需要的东西。推导要容易得多。
Yes. IMHO, overriding GetWebRequest() is the best solution to WebClient's limited functionalty. Before I knew about this option, I wrote lots of really painful code at the HttpWebRequest layer because WebClient almost, but not quite, did what I needed. Derivation is much easier.
另一种选择是使用常规WebClient类,但提出请求之前手动填充Cookie头,然后拔出集饼干头的响应。有对的CookieContainer类的辅助方法这使得创建和解析这些头容易:<一href=\"http://msdn.microsoft.com/en-us/library/system.net.cookiecontainer.setcookies.aspx\"><$c$c>CookieContainer.SetCookies()$c$c>和<一个href=\"http://msdn.microsoft.com/en-us/library/system.net.cookiecontainer.getcookieheader.aspx\"><$c$c>CookieContainer.GetCookieHeader()$c$c>,分别。
Another option is to use the regular WebClient class, but manually populate the Cookie header before making the request and then pull out the Set-Cookies header on the response. There are helper methods on the CookieContainer class which make creating and parsing these headers easier: CookieContainer.SetCookies()
and CookieContainer.GetCookieHeader()
, respectively.
我preFER前一种方法,因为它是调用者更容易,需要更少的重复code比第二个选项。另外,推导的方法的工作方式相同为多个扩展性方案(例如饼干,代理等)。
I prefer the former approach since it's easier for the caller and requires less repetitive code than the second option. Also, the derivation approach works the same way for multiple extensibility scenarios (e.g. cookies, proxies, etc.).
这篇关于使用的CookieContainer与WebClient类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!