将 CookieContainer 与 WebClient 类一起使用 [英] Using CookieContainer with WebClient class

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

问题描述

我之前曾将 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?

谷歌搜索 为此,找到了以下示例:

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

这是最好的方法吗?

推荐答案

是的.恕我直言,覆盖 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.).

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

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