2

请看以下代码:

    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 获取内容。

我该如何解决这个问题?

4

1 回答 1

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();
    }

如果您是 4.0 以下的 .NET 版本,您可能会遇到 CookieContainer 错误:检查此链接

于 2013-01-28T06:40:24.757 回答