Login to a website using POST and HttpRequest

感情迁移 提交于 2019-12-25 01:16:56

问题


There is a website I need to login using HttpRequest. The login form of said website uses POST method. I know how to use HttpRequest for pages with no protection, how can I login to a website using POST?


回答1:


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


来源:https://stackoverflow.com/questions/5979780/login-to-a-website-using-post-and-httprequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!