使用POST和HttpRequest登录网站

时间:2011-05-12 14:43:03

标签: c# .net httprequest

我需要使用HttpRequest登录网站。所述网站的登录表单使用POST方法。我知道如何对没有保护的页面使用HttpRequest,如何使用POST登录网站?

1 个答案:

答案 0 :(得分:1)

这个例子是http://www.netomatix.com的礼貌。 POST设置为后面代码中HttpWebRequest.Method处理程序中的OnClick属性。

示例表格

<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>

代码背后:

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();
}