且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对WebClient类使用CookieContainer

更新时间:2022-12-05 12:09:21

是的。 IMHO,重写GetWebRequest()是WebClient有限功能的***解决方案。在我知道这个选项之前,我在HttpWebRequest层写了很多痛苦的代码,因为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头,然后在响应中拉出Set-Cookies头。 CookieContainer类有助于方法,使创建和解析这些头更容易: CookieContainer.SetCookies() CookieContainer.GetCookieHeader()

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.

我更喜欢使用前一种方法,因为它对于调用者来说更容易,并且比第二个选项需要更少的重复代码。此外,对于多个可扩展性场景(例如,Cookie,代理等),推导方法工作方式相同。

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.).