以下函数是用 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#,而且我在将这种代码放在一起时遇到了问题。我已经尝试解决这个问题好几天了,但即使谷歌也没有帮助我,我一直在寻找解决方案谢谢!