.Net Core(C#) 使用WebClient执行请求时配置cookie的方法及示例代码

.Net Core(C#) 使用WebClient执行请求一些网页时,可能需要登陆或维护一下cookie,才能达到我们想要效果。本文就要介绍一下使用WebClient执行请求时设置cookie和维持维护cookie的方法及示例代码。

1、通过WebClient对象的Headers设置cookie

 WebClient wb = new WebClient();
 wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");
//设置一个cookie值
wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 
//设置多个cookie值
wb.Headers.Add(HttpRequestHeader.Cookie, 
              "cookiename1=cookievalue1;" +
              "cookiename2=cookievalue2");

2、重写WebClient的方法维护设置cookie

public class WebClientCookie : WebClient
{
    public WebClientCookie(CookieContainer container)
    {
        this.container = container;
    }
   public CookieContainer CookieContainer
   {
         get { return container; }
         set { container= value; }
    }
    // 设置自己想要添加的登陆信息等cookie
   public void SetCustCookie(string name,string value, string path,string domain)
    {
     CookieCollection cookies = new CookieCollection();
     cookies.Add(new Cookie(name.Trim(), value.Trim(), path, domain));
      container.Add(cookies);
     }
    private CookieContainer container = new CookieContainer();
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest r = base.GetWebRequest(address);
        var request = r as HttpWebRequest;
        if (request != null)
        {
            request.CookieContainer = container;
        }
        return r;
    }
    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    {
        WebResponse response = base.GetWebResponse(request, result);
        ReadCookies(response);
        return response;
    }
    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        ReadCookies(response);
        return response;
    }
    private void ReadCookies(WebResponse r)
    {
        var response = r as HttpWebResponse;
        if (response != null)
        {
            CookieCollection cookies = response.Cookies;
            container.Add(cookies);
        }
    }
}

相关文档.Net(C#) 后台使用webclient(客户端控制台程序)执行Get和Post请求的方法-CJavaPy

推荐阅读
cjavapy编程之路首页