How to use HttpWebRequest to login to website?

2020-07-30 01:54发布

问题:

I am trying to rewrite some server php code which logs into a website, using the canonical HttpWebRequest usage found all over the net on C# sites:

HttpWebRequest BuildPOST(string url, string parameters)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    byte[] bytes = Encoding.ASCII.GetBytes(parameters);
    Stream os = null;
    try
    { 
         request.ContentType = "application/x-www-form-urlencoded";
         equest.ContentLength = bytes.Length;
         os = request.GetRequestStream();
         os.Write(bytes, 0, bytes.Length); 
    }
    catch (WebException ex)
    {
         Console.WriteLine("{0} HttpPost: Request error", ex.Message);
    }
    finally
    {
         if (os != null)
         {
              os.Close();
         }
    }
    return request;
}

called using:

string login_url = "http://www.sailonline.org/community/accounts/login/";
string login_post_data = "next=/windy/run/{0}/&password={1}&username={2}";  // race, pwd, boat
HttpWebRequest req = BuildPOST(login_url, string.Format(login_post_data, race, pwd, user));

The original php is:

include 'phplib.php';

$url = "http://www.sailonline.org/community/accounts/login/";
$postdata = sprintf("next=/windy/run/%s/&password=%s&username=%s", $race, $key, $boat);
$html = get_pipe_output(build_post_url($url, $postdata));

However, the C# code does not generate the same response from the server as the php code. Instead I get a page asking for login details (which were correctly input in the post to begin with).

I am somewhat new to network programming, and just cannot seem to figure out why this is happeneing. I have snooped the packets from my code, the page serving the php and the original login page on the website in question and cannot see any difference betwen the requsts, only that the one issued from C# code does not have the expected response.
All I can think is perhaps the php functions do something I am unaware of ??

回答1:

You need to create and set a CookieContainer on the request. Without that your request wont succeed. Looks like the page is sending cookies with the response.

HTTP/1.1 200 OK
Date: Mon, 31 Jan 2011 23:53:23 GMT
Server: Apache
Expires: Mon, 31 Jan 2011 23:53:23 GMT
Vary: Cookie
Last-Modified: Mon, 31 Jan 2011 23:53:23 GMT
ETag: "ad806aa693ed8187c278f0fadfa92d01"
Cache-Control: max-age=0
Content-Type: text/html; charset=utf-8
Set-Cookie:  sailonlinesid=bcc2b5fe9980df3e741e8fe7279d61d4; Domain=.sailonline.org; expires=Mon, 14-Feb-2011 23:53:23 GMT; Max-Age=1209600; Path=/
Connection: close