C#对web客户端使用cookie httprequest
本文关键字:cookie httprequest 客户端 web | 更新日期: 2023-09-27 17:59:10
我通过httprequest和cookie在variable cookiecontanse中登录了网站。但现在我需要为webclient设置cookie get。我用了
webClient.Headers.Add(HttpRequestHeader.Cookie,cookiecontanse.ToString)
但不起作用。为什么?
用法:
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容器。