【问题标题】:How to submit http form using C#如何使用 C# 提交 http 表单
【发布时间】:2010-11-19 10:16:38
【问题描述】:

我有一个简单的 html 文件,例如

<form action="http://www.someurl.com/page.php" method="POST">
   <input type="text" name="test"><br/>
   <input type="submit" name="submit">
</form>

编辑:我可能对这个问题不够清楚

我想编写提交此表单的 C# 代码,就像我将上面的 html 粘贴到一个文件中,用 IE 打开它并用浏览器提交它。

【问题讨论】:

  • 这个表单应该在用户页面上还是您想以编程方式复制的东西?
  • 不,这是我想以编程方式复制的东西。
  • 我不明白你的问题。您不能直接提交带有服务器端代码的表单。 HTML 表单提交在客户端完成。
  • 对,我在这里找客户端代码。
  • 能否请您展示一下您的解决方案?

标签: c# .net html forms http-post


【解决方案1】:

这是我最近在接收 GET 响应的网关 POST 事务中使用的示例脚本。您是否在自定义 C# 表单中使用它?无论您的目的是什么,只需将字符串字段(用户名、密码等)替换为表单中的参数即可。

private String readHtmlPage(string url)
   {

    //setup some variables

    String username  = "demo";
    String password  = "password";
    String firstname = "John";
    String lastname  = "Smith";

    //setup some variables end

      String result = "";
      String strPost = "username="+username+"&password="+password+"&firstname="+firstname+"&lastname="+lastname;
      StreamWriter myWriter = null;

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      objRequest.Method = "POST";
      objRequest.ContentLength = strPost.Length;
      objRequest.ContentType = "application/x-www-form-urlencoded";

      try
      {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(strPost);
      }
      catch (Exception e) 
      {
         return e.Message;
      }
      finally {
         myWriter.Close();
      }

      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      using (StreamReader sr = 
         new StreamReader(objResponse.GetResponseStream()) )
      {
         result = sr.ReadToEnd();

         // Close and clean up the StreamReader
         sr.Close();
      }
      return result;
   } 

【讨论】:

  • 如果我使用此代码,我提交的页面不会获得信息。它仅在使用我引用的 html sn-p 时有效。
  • @JC:为什么这个解决方案不起作用?你没有得到你的“测试”输入值?在看到所有这些不被接受的答案后,我只是自己去解决这个问题,却发现我做的和 shanabus 做的完全一样。如果您希望以编程方式 POST 到表单,HttpWebRequest 确实是解决方案。请参阅这篇文章以获取另一个基本上做同样事情的示例csharpfriends.com/Forums/ShowPost.aspx?PostID=32254
  • 我提交的页面根据输入发送响应。如果我通过浏览器执行此操作,它只会发送正确的响应。也许它与php实现有关,我不知道。或者如下所述,我可能需要添加正确的标题。
  • 旁注:我必须添加一个“?”到我的变量字符串的开头(所有 URL 传递的变量的典型字符)以使连接正常工作。
【解决方案2】:

您的 HTML 文件不会直接与 C# 交互,但您可以编写一些 C# 使其表现得像 HTML 文件一样。

例如:有一个名为 System.Net.WebClient 的类,方法很简单:

using System.Net;
using System.Collections.Specialized;

...
using(WebClient client = new WebClient()) {

    NameValueCollection vals = new NameValueCollection();
    vals.Add("test", "test string");
    client.UploadValues("http://www.someurl.com/page.php", vals);
}

有关更多文档和功能,请参阅MSDN page.

【讨论】:

  • 这与我直接使用浏览器时得到的响应不同。
  • 您的浏览器发送了一堆标题。嗅探浏览器使用 Fiddler 或 Firebug 发送的 HTTP 请求。然后使用 client.Headers 属性复制这些标头。
【解决方案3】:

您可以使用HttpWebRequest 类来执行此操作。

例如here:

using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

【讨论】:

  • 不,这只是发送一个 URL。我在问如何以编程方式构造和提交表单。
  • 这也做 POST(见 WebRequest.Method)
  • 正如@JC 所说,这仅回答了如何发送 POST 请求;它没有回答如何在 HTTP 请求中构造表单。
【解决方案4】:
Response.Write("<script> try {this.submit();} catch(e){} </script>");

【讨论】:

    【解决方案5】:

    我需要一个按钮处理程序,它可以在客户端浏览器中创建一个表单发布到另一个应用程序。我遇到了这个问题,但没有看到适合我的情况的答案。这是我想出的:

          protected void Button1_Click(object sender, EventArgs e)
            {
    
                var formPostText = @"<html><body><div>
    <form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
      <input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" /> 
      <input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" /> 
    </form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
    ";
                Response.Write(formPostText);
            }
    

    【讨论】:

      【解决方案6】:

      我在 MVC 中遇到了类似的问题(导致我遇到了这个问题)。

      我收到了来自 WebClient.UploadValues() 请求的字符串响应形式的 FORM,然后我必须提交该请求 - 所以我不能使用第二个 WebClient 或 HttpWebRequest。该请求返回了字符串。

      using (WebClient client = new WebClient())
        {
          byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
          {
              { "test", "value123" }
          });
      
          result = System.Text.Encoding.UTF8.GetString(response);
        }
      

      我可以用来解决 OP 的解决方案是在代码末尾附加一个 Javascript 自动提交,然后使用 @Html.Raw() 将其呈现在 Razor 页面上。

      result += "<script>self.document.forms[0].submit()</script>";
      someModel.rawHTML = result;
      return View(someModel);
      

      剃刀代码:

      @model SomeModel
      
      @{
          Layout = null;
      }
      
      @Html.Raw(@Model.rawHTML)
      

      我希望这可以帮助任何发现自己处于相同情况的人。

      【讨论】:

        猜你喜欢
        • 2019-11-03
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 2017-06-20
        • 2016-03-21
        • 1970-01-01
        • 2012-04-08
        相关资源
        最近更新 更多