1

以下函数是用 C# 编写的,用于登录网站(使用 POST 方法并设置 Cookie)。

问题是,如果我第一次使用错误的用户名或密码登录,我将无法再次登录,直到我再次运行该程序。该函数执行一次,如果登录信息错误,几分钟后结束并出现以下错误:

Stream newStream = getRequest.GetRequestStream(); // open connection

用户代码未处理 WebException:超时已过期

我想寻求一点帮助以找出问题所在。在我看来,错误可能出在使用 CookieCollection - 如果登录不成功,我想删除所有现有的 cookie,但我无法弄清楚。我正在使用这个解决方案:

private bool Login(string name, string password) 
   { 
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://.../login-page/"); 
       request.CookieContainer = new CookieContainer(); 
       request.CookieContainer.Add(cookies); 
       //Get the response from the server and save the cookies from the first request.. 
       HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
       cookies = response.Cookies; 

       string sourceCode; 
       string getUrl = "http://.../login/"; 
       string postData = String.Format("username={0}&password={1}", name, password); 
       HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl); 
       getRequest.CookieContainer = new CookieContainer(); 
       getRequest.CookieContainer.Add(cookies); //recover cookies First request 
       getRequest.Method = WebRequestMethods.Http.Post; 
       getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; 
       getRequest.AllowWriteStreamBuffering = true; 
       getRequest.ProtocolVersion = HttpVersion.Version11; 
       getRequest.AllowAutoRedirect = true; 
       getRequest.ContentType = "application/x-www-form-urlencoded"; 

       byte[] byteArray = Encoding.ASCII.GetBytes(postData); 
       getRequest.ContentLength = byteArray.Length; 
       Stream newStream = getRequest.GetRequestStream(); // open connection 
       newStream.Write(byteArray, 0, byteArray.Length);  // Send the data. 
       newStream.Close(); 

       HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse(); 
       cookies = getResponse.Cookies; 
       using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) 
       { 
           sourceCode = sr.ReadToEnd(); 
       } 

       if (sourceCode.Contains("<div id='login'>Přihlášení se zdařilo</div>")) 
       { 
           return true; 
       } 
       return false; 
   }

代码来自:https ://stackoverflow.com/a/8542205/2715725

我真的很感激任何帮助。我不是那么喜欢 C#,而且我在将这种代码放在一起时遇到了问题。我已经尝试解决这个问题好几天了,但即使谷歌也没有帮助我,我一直在寻找解决方案谢谢!

4

3 回答 3

0

看起来故障很可能出在您发布用户名和密码的外部站点上。您确定它在您第一次正确验证时以及在登录失败后设法验证时都会显示该确切消息吗?直接在该站点上尝试这两种操作以找出答案。

于 2013-09-06T07:34:44.207 回答
0

问题解决了

我将此添加到我的函数中:

request.KeepAlive = false;
response.Close();
getRequest.KeepAlive = false;
getResponse.Close();
于 2013-09-06T16:24:19.763 回答
0

将此添加到您的函数中:

request.KeepAlive = false;
response.Close();
getRequest.KeepAlive = false;
getResponse.Close();
于 2013-09-07T23:35:08.413 回答