Login to a website using POST and HttpRequest
There is a website I need to login using HttpRequest. The login form of said webs开发者_如何学JAVAite uses POST method. I know how to use HttpRequest for pages with no protection, how can I login to a website using POST?
This example is by the courtesy of http://www.netomatix.com.
The POST
is set to the HttpWebRequest.Method
property in the OnClick
handler in code behind.
Example form:
<form name="_xclick" target="paypal"
action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="me@mybiz.com">
<input type="hidden" name="item_name" value="HTML book">
<input type="hidden" name="amount" value="24.99">
<input type="image" src="http://www.paypal.com/images/sc-but-01.gif"
border="0" name="submit" alt="Make payments with PayPal!">
<input type="hidden" name="add" value="1">
</form>
Code behind:
private void OnPostInfoClick(object sender, System.EventArgs e)
{
string strId = UserId_TextBox.Text;
string strName = Name_TextBox.Text;
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strId;
postData += ("&username="+strName);
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://localhost/MyIdentity/Default.aspx");
myRequest.Method = "POST"; // <<--- This is the key word of the day
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}
精彩评论