Send POST request in C# like a web page does? [dup

2019-02-20 04:53发布

问题:

Possible Duplicate:
How to simulate browser HTTP POST request and capture result in C#

I have the following form in my web page...

<input type="text" tabindex="1" id="username" name="username" size="30"/>
<input type="password" tabindex="2" id="password" name="password" size="30"/>

I use these to log into my website.
But I want to provide this functionality in my application as well.
How do I use a HTTP web request to send the user and password to my verification page?

回答1:

Scott Hanselman has a great post about this:

http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx

(quite similar to @The Mask response, but a bit more verbose on the explanation)



回答2:

Try using the WebClient class. example:

var url = @"..."; 
var nvc = new System.Collections.Specialized.NameValueCollection();
nvc.Add("username", "username");
nvc.Add("password", "password");
var client = new System.Net.WebClient();
var data = client.UploadValues(url, nvc);
var res = System.Text.Encoding.ASCII.GetString(data);
Console.WriteLine(res);
Console.ReadLine();


回答3:

How to simulate browser HTTP POST request and capture result in C#