0

I'm having trouble converting this into a HTTPWebRequest. I got this to work perfectly, using a WebBrowser, but whenever I try to make a HTTPWebRequest it fails. I'm not sure what I'm doing wrong.

Working code:

private void Login()
{
    WebBrowser b = new WebBrowser();
    b.ScriptErrorsSuppressed = true;
    username = textBox1.Text;
    password = textBox2.Text;
    string PostData = string.Format("username={0}&password={1}&rk24={2}", username, password, rk24);
    ASCIIEncoding enc = new ASCIIEncoding();
    b.Navigate(url, "", enc.GetBytes(PostData), "Content-Type: application/x-www-form-urlencoded\r\n");
    b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}

private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser b = sender as WebBrowser;
    string response = b.DocumentText;
    if (response.Contains("Sign out"))
    {
        this.Text = "LOGGED IN";
        b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
    }
    if (response.Contains("your info was incorrect"))
    {
        b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
        this.Text = "LOGIN ERROR";
        MessageBox.Show("Invalid username or password!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

This is my attempt at an HTTPWebRequest that does NOT work...

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    ASCIIEncoding enc = new ASCIIEncoding();
    string postData = string.Format("username={0}&password={1}&rk24={2}", user, pass, rk24);
    byte[] data = enc.GetBytes(postData);
    request.ContentLength = data.Length;
    Stream stream = request.GetRequestStream();
    stream.Write(data, 0, data.Length);
    stream.Close();
    WebResponse response = request.GetResponse();
    stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    string responseFromServer = reader.ReadToEnd();
    if(responseFromServer.Contains("Sign out"))
    {
        MessageBox.Show("Logged In!");
    }
    if (responseFromServer.Contains("your info was incorrect"))
    {
        MessageBox.Show("Invalid username or password");
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397

1 Answers1

0

Login systems mostly use cookies and sessions to provide authentication. Webrequests do ofcourse not set cookies etc. This is the task of a browser. This is most likely why the webbrowser verion does work as this processes JS and saves cookies and all that. You can save cookies however. Take a look at the CookieContainer class.

I like to extend the WebClient class for these cases. This is a more abstract version which internally uses the webrequests etc..

perhaps this snippet will be of assistance: (maybe print the cookies? you should definitely check this with a browser if this is the problem)

 class MyWebClient : WebClient
{
    Uri _responseUri;
    public CookieContainer CookieContainer;

    public Uri ResponseUri
    {
        get { return _responseUri; }
    }

    public MyWebClient()
    {
        CookieContainer = new CookieContainer(); //TODO improve with read/write actions from disk. (binaryformatter)
    }

    public string GetCookieValue(string name)
    {
        return CookieContainer.GetCookies(_responseUri).Cast<Cookie>().First(c => c.Name == name).Value;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);

        var webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = CookieContainer;
        }

        return request;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        _responseUri = response?.ResponseUri;
        return response;
    }
}
sommmen
  • 6,570
  • 2
  • 30
  • 51