对WebClient类使用CookieContainer

对WebClient类使用CookieContainer

本文介绍了对WebClient类使用CookieContainer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前使用过CookieContainer与HttpWebRequest和HttpWebResponse会话,但现在,我想使用它与WebClient。据我所知,没有像HttpWebRequests( request.CookieContainer )的内置方法。 如何在CookieContainer中从WebClient收集Cookie?

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?

我 for this and found :

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;
    }
}

这是最好的方法吗? p>

Is this the best way to do it?

推荐答案

是的。 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类有助于方法,使创建和解析这些头更容易:和。

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

这篇关于对WebClient类使用CookieContainer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:12