3

我目前正在研究一个可以帮助我使用 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;
    }
}
4

3 回答 3

4

由于this.cookies最初为 null,因此您的代码永远不会进入循环

foreach (KeyValuePair<string, Cookie> pair in this.cookies)
{
     Console.WriteLine(" Sent cookie: " + pair.Value.Name + " = " + pair.Value.Value);
     request.CookieContainer.Add(pair.Value);
}

你从未见过的坏部分request.CookieContainer是 null (否则你会得到null 引用异常),这会告诉你有问题。

由于request.CookieContainer为 null,HttpWebResponse 永远不会获取返回的 cookie。

解决方案:简单,只需添加

if (request.CookieContainer == null) 
         request.CookieContainer = new CookieContainer();

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

PS:您可能想阅读有关 c# 中的命名约定的这个问题。

PS2:在request使用变量名的方法request中不会提高可读性。

于 2013-08-26T19:07:49.140 回答
3

我遇到了同样的问题,所以我添加了request.AllowAutoRedirect=false;,现在我可以获取 cookie:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
...
request.Method = "POST";
request.AllowAutoRedirect=false;
于 2015-08-28T21:52:27.840 回答
1

如果HttpWebResponse对象的Cookies集合为空,则意味着响应没有新的 cookie。要访问所有 cookie 以获取请求和响应,请改为从HttpWebRequest对象中读取 cookie,如下所示:

foreach (Cookie newCookie in request.Cookies)
{
    // Do something with cookies here for next request
}
于 2013-08-26T17:21:29.350 回答