如何使用C#来提交HTTP表单(How to submit http form using C#)

2019-06-18 11:17发布

我有一个简单的HTML文件,如

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

编辑:我可能不会有这样一个问题不够清晰

我想写它提交此表中时会出现有我粘贴上面的HTML到一个文件中,用IE打开它,并在浏览器提交它完全相同的方式的C#代码。

Answer 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;
   } 


Answer 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页面。



Answer 3:

您可以使用的HttpWebRequest类来这样做。

例如在这里 :

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>

*/


Answer 4:

Response.Write("<script> try {this.submit();} catch(e){} </script>");


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


Answer 6:

我曾在MVC类似的问题(这导致我这个问题)。

我接收FORM如从WebClient.UploadValues()请求,该请求然后我需要提交的字符串响应 - 所以我不能使用第二个Web客户端或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()以使其剃刀页面上。

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

剃刀代码:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

我希望这可以帮助任何人谁发现自己在同样的情况。



文章来源: How to submit http form using C#