我有一个自定义的Web浏览器控件,其中包含一个带有cookie容器的http客户端。我重写了WebBrowser.Navigate()方法,因此它使用了http客户端和GetWebRequest()& http客户端中的GetWebResponse()。 有没有办法检测是否添加了新的cookie? (我不确定http客户端在进行更改时是否使用CookieContainer.Add()方法)
导航方法:
(WebClient是http客户端)
public new void Navigate(Uri url)
{
WebClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
WebClient.DownloadData(url);
var cookies = CookieTools.LoadCookies(User).GetCookies(url);
var prefCookie = cookies["PREF"];
base.Navigate(url, "", null, "Cookie: " + prefCookie?.Value + Environment.NewLine);
}
http客户端方法覆盖#1
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
var httpRequest = request as HttpWebRequest;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
httpRequest.ContentType = "text/html; charset=UTF-8";
httpRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8,cs;q=0.6");
httpRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
httpRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
httpRequest.CookieContainer = CookieContainer;
return httpRequest;
}
http客户端方法覆盖#2
我正在保存来自Navigate()请求的所有Cookie
protected override WebResponse GetWebResponse(WebRequest request)
{
var httpResponse = base.GetWebResponse(request) as HttpWebResponse;
foreach (Cookie cookie in httpResponse.Cookies)
CookieContainer.Add(cookie);
CookieTools.SaveCookies(CookieContainer, User);
return httpResponse;
}