使用C#编程登录网站

本文关键字:网站 登录 编程 使用 | 更新日期: 2023-09-27 18:28:16

我想用C#登录这个网站:这是我的尝试,但它把我送到了第一页。没有给我返回下一个页面,登录后应该可以看到,请帮助我解决这个问题:

string formParams = 
string.Format("mail={0}&password={1}", store@admin.com", "admin");
      string cookieHeader;
      WebRequest req = WebRequest.Create("http://muslimgowns.com/dashboard/login/public_login");
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(formParams);
            req.ContentLength = bytes.Length;
            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            WebResponse resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];
            using (StreamReader sr = new  StreamReader(resp.GetResponseStream()))
            {
                string pageSource = sr.ReadToEnd();
                File.AppendAllText("first.txt", pageSource);
            }
            string pageSource1;
            string getUrl = "http://muslimgowns.com/dashboard/home";
            WebRequest getRequest = WebRequest.Create(getUrl);
            getRequest.Headers.Add("Cookie", cookieHeader);
            WebResponse getResponse = getRequest.GetResponse();
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                pageSource1 = sr.ReadToEnd();
                File.AppendAllText("second.txt", pageSource1);
            }
        }

使用C#编程登录网站

似乎向public_login发送的第一个GET请求返回了一定数量的cookie,之后带有凭据的POST请求必须发送到login_access而不是public_login

使用HttpWebRequest而不是WebRequest,并通过设置其cookie容器来提供帮助,实际上,服务器用HTTP 302 Redirect响应POST请求,HttpWebRequest自动遵循此重定向并下载仪表板。

始终使用Fiddler、Wireshark或Network Monitor等http跟踪工具或浏览器的开发工具来查看收到的内容(cookie、标头等)和发回的内容。这就是我得到这一切的原因。

修复方法如下:

string formParams = string.Format("mail={0}&password={1}", "store@admin.com", "admin");
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest req = WebRequest.CreateHttp("http://muslimgowns.com/dashboard/login/public_login");
req.CookieContainer = cookieContainer;
req.GetResponse(); // This is just to get the initial cookies returned by the public_login
req = WebRequest.CreateHttp("http://muslimgowns.com/dashboard/login/login_access");
req.CookieContainer = cookieContainer; // Set the cookie container which contains the cookies returned by the public_login
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string pageSource = sr.ReadToEnd();
    File.AppendAllText("first.txt", pageSource); // Dashboard is returned.
}