c# HttpWebRequest网站登录

本文关键字:登录 网站 HttpWebRequest | 更新日期: 2023-09-27 18:06:37

我正试图从web浏览器控制切换到http请求,以实现自动化任务的速度。使用这个函数,我可以发布数据并接收一个登录页面,但不返回cookie并将其添加到cookie列表中,因此登录会话不会传递给下一个请求。

    //an example call        
    test("http://websitename.com/loginpage.php", "username=foo&password=123456");
    private string test(string url, string data)
    {
        string responseFromServer;
        byte[] byteArray;
        Stream dataStream;
        HttpWebRequest request;
        HttpWebResponse response;
        StreamReader reader;

        responseFromServer = string.Empty;
        try
        {
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.KeepAlive = true;
            request.ContentType = "application/x-www-form-urlencoded";
            byteArray = Encoding.UTF8.GetBytes(data);
            request.ContentLength = byteArray.Length;
            request.CookieContainer = new CookieContainer();
            foreach(Cookie a in cookies)
                request.CookieContainer.Add(a);
            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            response = request.GetResponse() as HttpWebResponse;
            foreach(Cookie a in response.Cookies)
                cookies.Add(a);
            dataStream = response.GetResponseStream();
            reader = new StreamReader(dataStream);
            responseFromServer = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();
        }
        catch (Exception x)
        {
            x.ToString();
        }
        return responseFromServer;
    }

如何保持登录状态?

c# HttpWebRequest网站登录

这是最终答案:

string url = "http://www.ABC/MemberShip/Login.aspx";// HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = myCookieContainer;
request.Method = "GET";
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
// get the page ViewState                
string viewStateFlag = "id='"__VIEWSTATE'" value='"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("'"", i);
string viewState = srcString.Substring(i, j - i);
// get page EventValidation                
string eventValidationFlag = "id='"__EVENTVALIDATION'" value='"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("'"", i);
string eventValidation = srcString.Substring(i, j - i);
string submitButton = "LoginButton";
// UserName and Password
string userName = "userid";
string password = "password";
// Convert the text into the url encoding string
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
// Concat the string data which will be submit
string formatString =
         "txtUserName={0}&txtPassword={1}&btnSignIn={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
string postString =
         string.Format(formatString, userName, password, submitButton, viewState, eventValidation);
// Convert the submit string data into the byte array
byte[] postData = Encoding.ASCII.GetBytes(postString);
// Set the request parameters
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Referer = url;
request.KeepAlive = false;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = myCookieContainer;
System.Net.Cookie ck = new System.Net.Cookie("TestCookie1", "Value of test cookie");
ck.Domain = request.RequestUri.Host;
request.CookieContainer.Add(ck);
request.CookieContainer.Add(response.Cookies);
request.ContentLength = postData.Length;
// Submit the request data
System.IO.Stream outputStream = request.GetRequestStream();
request.AllowAutoRedirect = true;
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();

// Get the return data
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
Response.Write(srcString);
Response.End();

这个帖子似乎有一个积极的投票计数的答案:c#在httpwebrequest上保持会话id

在对服务器的第一个请求中创建一个CookieContainer实例,而不是为下一个请求创建一个新的实例,而是重用该实例。