在winforms中使用HttpWebRequest传递cookie?

时间:2013-01-28 06:34:48

标签: c# winforms cookies httpwebrequest cookiecontainer

请参阅以下代码:

    objCookieContainer = new CookieContainer();

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://website.com/login.php?user=xxx&pass=xxx");
    request.Method = WebRequestMethods.Http.Get;
    request.Timeout = 15000;
    request.Proxy = null;
    request.CookieContainer = objCookieContainer;

    HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create("http://website.com/page.php?link=url");
    newRequest.Method = WebRequestMethods.Http.Get;
    newRequest.Timeout = 15000;
    newRequest.Proxy = null;
    newRequest.CookieContainer = objCookieContainer;

    HttpWebResponse response = null;

    response = (HttpWebResponse)request.GetResponse();
    string readerRequest = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();

    response = (HttpWebResponse)newRequest.GetResponse();
    string readerNewRequest = new StreamReader(response.GetResponseStream()).ReadToEnd();

在使用request.GetResponse()之后,cookie成功填充了数据并且它具有了它的身份验证代码并且也填充了readerRequest,之后我调用newRequest.GetResponse()但是readerNewRequest为空,我尝试做很多事情,但总是相同的结果,我解决这个问题的唯一方法是使用WebBrowser对象,我在其中传递url,我能够使用WebBrowser.DocumentStream获取内容。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

    private void button1_Click(object sender, EventArgs e)
    {
        var objCookieContainer = new CookieContainer();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://website.com/login.php?user=xxx&pass=xxx");
        request.Method = WebRequestMethods.Http.Get;
        request.Timeout = 15000;
        request.Proxy = null;
        request.CookieContainer = objCookieContainer;

        HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create("http://website.com/page.php?link=url");
        newRequest.Method = WebRequestMethods.Http.Post;
        newRequest.Timeout = 15000;
        newRequest.Proxy = null;


        HttpWebResponse response = null;

        response = (HttpWebResponse)request.GetResponse();
        //once you read response u need to add all cookie sent in header to the 'objCookieContainer' so that it can be forwarded on second response
        foreach (Cookie cookie in response.Cookies)
        {
            objCookieContainer.Add(cookie);
        }
        string readerRequest = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();


        //since you have added the cookies, this must response fine now
        newRequest.CookieContainer = objCookieContainer;
        response = (HttpWebResponse)newRequest.GetResponse();
        string readerNewRequest = new StreamReader(response.GetResponseStream()).ReadToEnd();
    }

如果您的.NET版本低于4.0,您可能会遇到CookieContainer错误:检查This Link