我目前正在使用以下代码来获取网站的 cookie:
bool IsLoginSuccessful = false;
try
{
//Get Token and Authorization URL
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("https://updates.site.com/download");
wr.AllowAutoRedirect = true;
WebResponse response = wr.GetResponse();
response.Close();
string data = response.ResponseUri.OriginalString;
string ssoToken = data.Split('=')[1];
string authData = String.Format("ssousername={0}&password={1}&site2pstoretoken={2}", username, password, ssoToken);
string ssoServer = response.ResponseUri.Scheme + "://" + response.ResponseUri.Host;
string ssoAuthUrl = "sso/auth";
// now let's get our cookie for the download
byte[] dataBytes = Encoding.UTF8.GetBytes(authData);
string url = ssoServer + "/" + ssoAuthUrl;
wr = (HttpWebRequest)HttpWebRequest.Create(url);
//MyCookies is a CookieContainer I use to store the login cookies
wr.CookieContainer = MyCookies;
wr.Method = "POST";
wr.ContentLength = dataBytes.Length;
wr.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = wr.GetRequestStream();
dataStream.Write(dataBytes, 0, dataBytes.Length);
dataStream.Close();
response = wr.GetResponse();
response.Close();
if (wr.CookieContainer.Count > 0)
{
IsLoginSuccessful = true;
}
}
我想知道是否有办法使用 WebClient 或从它继承的类来获取 cookie 而不是使用 HttpRequest?