I need to login to a website a download the source code from various pages when logged in. I am able to do this quite easily when using the Windows Forms WebBrowser class, however this is not appropiate and I need to be able to do this with WebRequest or one of the others. Unfortunately it doesn't like how I am handling the cookies.
I am using the following code and get the following response: {"w_id":"LoginForm2_6","message":"Please enable cookies in your browser so you can log in.","success":0,"showLink":false}
string url2 = "%2Fapp%2Futils%2Flogin_form%2Fredirect%2Fhome";
string login = "username";
string password = "password";
string w_id = "LoginForm2_6";
string loginurl = "http://loginurl.com";
string cookieHeader;
WebRequest req = WebRequest.Create(loginurl);
req.Proxy = WebRequest.DefaultWebProxy;
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
req.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
req.Method = "POST";
string postData = string.Format("w_id={2}&login={0}&password={1}&url2={3}", login, password, w_id, url2);
byte[] bytes = Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource = "";
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
richTextBox1.Text = pageSource;
If anyone could tell me where I'm going wrong, it would be greatly appreciated.
Also, to let you know, if I use the following with the webbrowser class, it works in fine:
b.Navigate(fullurl, "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");