The following function is wrote in C#, and it's used for logging in to a website (using POST Method and setting up Cookies).
The problem is that if my first login with bad username or password, I cannot log in again until i run the program again. The function is executed once, and if the login information is wrong, it ends after few minutes with this error:
Stream newStream = getRequest.GetRequestStream(); // open connection
WebException was unhandled by user code: timeout expired
I would like to ask for a little help to find out what is wrong. In my opinion, the mistake could be in the use of CookieCollection - I would like to delete all existing cookies in case of unsuccessful login, but I cannot figure it out. I'm using this solution:
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;
}
Code from: https://stackoverflow.com/a/8542205/2715725
I would really appreciate any kind of help. I'm not that into C# and I have problems to put this kind of code together. I have been trying to solve this for days, but even Google haven't helped me, I was looking for the solutin everywhere Thank you!