C#使用cookies登录网站

C#使用cookies登录网站,c#,http,cookies,httpwebrequest,httpwebresponse,C#,Http,Cookies,Httpwebrequest,Httpwebresponse,几天来,我一直试图让我的程序登录到一个网站,但都没有用。我相信我有一点是正确的(尤其是需要发布的数据格式) 然而,我很难弄清楚我到底遇到了什么问题。该网站需要cookies来验证登录,我不知道如何处理cookies。我尝试过跟踪这么多谷歌的搜索结果,这很愚蠢,但没有一个能很好地解释我需要知道的是什么 为了实现这个登录,我使用了HttpWebRequest和HttpWebResponse。我使用的代码主要是从没有解决我的问题的其他堆栈溢出问题组合而来的。本质上,这意味着我不完全理解使用HTTP登录

几天来,我一直试图让我的程序登录到一个网站,但都没有用。我相信我有一点是正确的(尤其是需要发布的数据格式)

然而,我很难弄清楚我到底遇到了什么问题。该网站需要cookies来验证登录,我不知道如何处理cookies。我尝试过跟踪这么多谷歌的搜索结果,这很愚蠢,但没有一个能很好地解释我需要知道的是什么

为了实现这个登录,我使用了HttpWebRequest和HttpWebResponse。我使用的代码主要是从没有解决我的问题的其他堆栈溢出问题组合而来的。本质上,这意味着我不完全理解使用HTTP登录网站所需的过程。我确实安装了Fiddler,我还使用Chrome开发者工具监控网络流量,并将我的帖子与网站的帖子进行比较

这是我的密码:

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;

namespace FormPOSTing
{
    class Program
    {
        static void Main(string[] args)
        {
            // URL of the login form and the data that needs to be posted
            string formURL = "https://www.pogo.com/action/pogo/login.do";
            string postData = "screenname=" + "Username" + "&password=" + "Password" + "&remember_password_hidden=" + "true" + "&signin=" + "Sign in";
            byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);

            var request = (HttpWebRequest)WebRequest.Create(formURL);
            request.CookieContainer = new CookieContainer();
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = dataBytes.Length;

            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(dataBytes, 0, dataBytes.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }
    }
现在,页面返回的URI就是这个页面:

用户名和密码是什么并不重要,因为它总是返回该页面。它从未达到可以尝试登录的程度


有人能告诉我更多关于如何工作以及如何实现成功登录的信息吗?

您必须在请求之间保存cookie jar
CookieContainer
。每次你的饼干罐被销毁时,里面所有的饼干都会被销毁。现在,您已经将jar的生存期与单个请求的生存期绑定在一起

这样更正:

namespace FormPOSTing
{
    class Program
    {
        static CookieContainer cookieJar = new CookieContainer();
        static void Main(string[] args)
            request.CookieContainer = cookieJar;
        }
    }
}

您必须跨请求持久化cookie jar
CookieContainer
。每次你的饼干罐被销毁时,里面所有的饼干都会被销毁。现在,您已经将jar的生存期与单个请求的生存期绑定在一起

这样更正:

namespace FormPOSTing
{
    class Program
    {
        static CookieContainer cookieJar = new CookieContainer();
        static void Main(string[] args)
            request.CookieContainer = cookieJar;
        }
    }
}