我目前正在研究一个可以帮助我使用 cookie 和 POST 参数创建 WebRequest 的类。但是 response.cookies 总是空的。如何获取返回的 cookie 并将它们与下一个请求一起发送?
class WebHandler
{
private string lasturl = "";
private Dictionary<string, Cookie> cookies;
public string lastContent;
public WebHandler()
{
cookies = new Dictionary<string, Cookie>();
}
public HttpWebResponse request(string address)
{
lasturl = address;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
foreach (KeyValuePair<string, Cookie> pair in this.cookies)
{
Console.WriteLine(" Sent cookie: " + pair.Value.Name + " = " + pair.Value.Value);
request.CookieContainer.Add(pair.Value);
}
request.Method = "GET";
if(lasturl != "")
request.Referer = lasturl;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
foreach (Cookie newCookie in response.Cookies)
{
Console.WriteLine(" new cookie: " + newCookie.Name + " = " + newCookie.Value);
this.cookies[newCookie.Name] = newCookie;
}
lastContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
return response;
}
public HttpWebResponse request(string address, Dictionary<string, string> postParameters)
{
lasturl = address;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
foreach (KeyValuePair<string, Cookie> pair in this.cookies)
{
Console.WriteLine(" Sent cookie: " + pair.Value.Name + " = " + pair.Value.Value);
request.CookieContainer.Add(pair.Value);
}
request.Method = "POST";
string postData = "";
foreach (string key in postParameters.Keys)
postData += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postParameters[key]) + "&";
byte[] data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
foreach (Cookie newCookie in response.Cookies)
{
Console.WriteLine(" new cookie: " + newCookie.Name + " = " + newCookie.Value);
this.cookies[newCookie.Name] = newCookie;
}
lastContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
return response;
}
}