C#在网页中保留Cookie和会话

时间:2015-07-14 13:35:04

标签: c# session cookies

我在这里尝试过很多例子,而且谷歌仍然无法保存我的登录信息。我已经调试并看到它发送302重定向并且我的登录成功。我相信。然后我将它发送到下一页,但保留从登录响应中获得的cookie。但我还是退出了。这是我的代码,除了网址和登录信息。我已经验证了我的POST参数。我首先要求会话cookie,然后登录然后进入重定向页面。所有的帮助都是主要的赞赏,这是一个巨大的头痛。

    HttpWebRequest GetRequest(string Site, CookieContainer Cookies, string SendType)
    {

        HttpWebRequest request = WebRequest.Create(Site) as HttpWebRequest;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
        request.CookieContainer = Cookies; // Assign it some cookies 
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = SendType; 
        return request; 
    }

    private string GetLoggedInPage(string username, string password, string loginPage, string redirectPage)
    {

        string formParams = string.Format("login={0}&password={1}", username, password);

        // cookies to use for multiple requests
        var cookies = new CookieContainer(); // Create cookies!



        var request= GetRequest(loginPage, cookies, "POST");


        //Send params off 
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);

        using (Stream loginStream = request.GetRequestStream())
        {
            loginStream.Write(bytes, 0, bytes.Length);
        }



        request.GetResponse().Dispose(); // removed some code here, no need to read response manually



        request= GetRequest(redirectPage, cookies, "GET");



        using (WebResponse getResponse = request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                var result = sr.ReadToEnd();//Read logged in webpage
                return  Convert.ToString(result); 
            }

        }


        return "<Html></html>"; //Return blank page in case the using above didn't work correctly. 



    }

以下代码经过重构并正常运行。我按照下面的KoBE的建议,但它仍然无法正常工作。问题结果是针对框架4.5.2我针对4.0和以下功能工作。只需发送GetLoggedInPage你的用户名,传递,登录网址和目标网址,它就会给你一个字符串。我要把它变成一个类并使用它。

请记得保存您的Cookie人员!

void WriteParams(string Params, HttpWebRequest webrequestStream)
{
    byte[] bytes = Encoding.ASCII.GetBytes(Params);


    using (Stream requestStream = webrequestStream.GetRequestStream())
    {
        requestStream.Write(bytes, 0, bytes.Length);
    }


}


 HttpWebRequest GetRequest(string Site, ref CookieContainer Cookies, string SendType)
{

    HttpWebRequest request = WebRequest.Create(Site) as HttpWebRequest;
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
    request.CookieContainer = Cookies; // Assign it some cookies 
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = SendType; 
    return request; 
}

private string GetLoggedInPage(string username, string password, string loginPage, string redirectPage)
{

    string formParams = string.Format("login={0}&password={1}", username, password);

    // cookies to use for multiple requests
    var cookies = new CookieContainer(); // Create cookies!



    HttpWebRequest request= GetRequest(loginPage, ref cookies, "POST");


    //Send params off 

    WriteParams(formParams, request);


    request.GetResponse();// .Dispose(); // removed some code here, no need to read response manually



    request= GetRequest(redirectPage, ref cookies, "GET");



    using (WebResponse getResponse = request.GetResponse())
    {
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            var result = sr.ReadToEnd();//Read logged in webpage
            return  Convert.ToString(result); 
        }

    }


    return "<Html></html>"; //Return blank page in case the using above didn't work correctly. 



}

1 个答案:

答案 0 :(得分:1)

编辑:我终于看了你的代码。看起来你只是错过了用户代理。请在底部查看修改后的代码。

首先,我会改变这个:

var cookies = new CookieContainer(); // Create cookies!
TheRequest.CookieContainer = new CookieContainer();

对此:

var cookies = new CookieContainer(); // Create cookies!
TheRequest.CookieContainer = cookies;

这将阻止您需要:

foreach (Cookie c in TheResponse.Cookies)//Get response cookie
{
    cookies.Add(c);
}
TheRequest.CookieContainer = cookies;

无需创建两个cookie容器,然后从一个容器复制到另一个容器容器,只需将原始容器设置为复制的版本。

我不确定,但这可以解决您的问题,具体取决于CookieContainer在后台实际执行的工作量,尤其是Uri特定的Cookie,或者您有什么。

https://www.pucatrade.com/dashboard您使用的网址是否正常?另外,为什么要尝试多次登录?

修改后的代码

string username = "your-user";
string pass = "your-pass";
string loginPage = "https://pucatrade.com/login";
string redirectPage = "https://pucatrade.com/dashboard";
string formParams = string.Format("login={0}&password={1}", username, pass);

// cookies to use for multiple requests
var cookies = new CookieContainer(); // Create cookies!

var request = WebRequest.Create(loginPage) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
request.CookieContainer = cookies; // Assign it some cookies 
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
request.ContentLength = bytes.Length;
using (Stream loginStream = request.GetRequestStream())
{
    loginStream.Write(bytes, 0, bytes.Length);
}

request.GetResponse().Dispose(); // removed some code here, no need to read response manually

request = WebRequest.Create(redirectPage) as HttpWebRequest; //we know we get redirected too here, so just go there. 
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
request.CookieContainer = cookies; // Assign it some cookies 
request.Method = "GET";

using (WebResponse getResponse = request.GetResponse())
{
    using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
    {
        var result = sr.ReadToEnd();//Read logged in webpage
    }
}