C#使用cookie httprequest到webclient

时间:2014-04-20 19:32:01

标签: c# cookies httprequest webclient

我通过http请求和cookie在变量cookiecontainer中记录了网站。但现在我需要为webclient设置cookie。我使用了行

 webClient.Headers.Add(HttpRequestHeader.Cookie,cookiecontanse.ToString) 

但不行。为什么?

1 个答案:

答案 0 :(得分:0)

用法:

        CookieContainer cookieJar = new CookieContainer();
        cookieJar.Add(new Cookie("my_cookie", "cookie_value", "/", "mysite"));

        CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);

        string response = client.DownloadString("http://example.com/response_with_cookie_only.php");

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; }
    public Uri Uri { get; set; }

    public CookieAwareWebClient()
        : this(new CookieContainer())
    {
    }

    public CookieAwareWebClient(CookieContainer cookies)
    {
        this.CookieContainer = cookies;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = this.CookieContainer;
        }
        HttpWebRequest httpRequest = (HttpWebRequest)request;
        httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        return httpRequest;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

        if (setCookieHeader != null)
        {
            //do something if needed to parse out the cookie.
            if (setCookieHeader != null)
            {
                Cookie cookie = new Cookie(); //create cookie
                this.CookieContainer.Add(cookie);
            }
        }
        return response;
    }
}

您将看到GetWebRequest和GetWebResponse的两个重写方法。可以重写这些方法来处理cookie容器。