如何以编程方式POST HTML表单并获得响应

时间:2014-02-28 05:21:06

标签: c# javascript html

我有一个获取用户名和密码的表单,在提交后会显示该帐户的一些信息。表格是:

<form id="LoginForm" target="Window81525062.79020184" action="Login.aspx" method="post" name="LoginForm">

      <input id="userID" type="text" maxlength="20" style="WIDTH: 160px; HEIGHT: 24px" onkeypress="CheckEnter()">

      <input id="Password" type="password" maxlength="20" style="WIDTH: 160px; HEIGHT: 24px" onkeypress="CheckEnter()">

      <div id="b2" class="social-media-shareTAK" style="width: 60px;">
          <div class="inner"></div>
          <ul>
              <li>
                  <a title="enter" target="_blank">
                       <img src="/DL/Classes/BUTTON/images/Login.png" alt="" style="width: 38px; height: 38px; margin-top: 4px; cursor: pointer; position: absolute; left: 7px;">
                  </a>
              </li>
          </ul>
       </div>
</form>

现在我想从数据库输入大约100个帐户用户名和密码,并将这些帐户的信息存储到另一个数据库。我该怎么做? (我更喜欢C#但是如果有更好的方法请告诉我)谢谢:)

1 个答案:

答案 0 :(得分:2)

这是一个C#示例(服务器端代码提供了更好的控制,所以我建议)

        StringBuilder postData = new StringBuilder();

        postData.Append("USERNAME_FIELD_NAME =" + HttpUtility.UrlEncode("USERNAME") + "&");
        postData.Append("PASSWORD_FIELD_NAME =" + HttpUtility.UrlEncode("PASSWORD"));

        // Now to Send Data.
        StreamWriter writer = null;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(THE_URL);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.ToString().Length;
        try
        {
            writer = new StreamWriter(request.GetRequestStream());
            writer.Write(postData.ToString());

        HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();                     

        //Now, we read the response (the string), and output it.
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        Console.WriteLine(_Answer.ReadToEnd());

        }
        finally
        {
            if (writer != null)
                writer.Close();
        }

来源/ HowTo's:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

http://forums.asp.net/t/1048041.aspx?How+to+programmatically+POST+data+to+an+aspx+page+

How to simulate HTTP POST programatically in ASP.NET?