如何使用C#提交http表单
我有一个简单的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打开它,然后用浏览器提交。
以下是我最近在接收GET响应的网关POST事务中使用的示例脚本。 你用自定义的C#forms吗? 无论您的目的是什么,只需用表单中的参数replacestring字段(用户名,密码等)即可。
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文件不会直接与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); }
有关更多文档和function,请参阅MSDN页面。
您可以使用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> */
Response.Write("<script> try {this.submit();} catch(e){} </script>");
我有一个类似的问题在MVC(这导致我这个问题)。
我从WebClient.UploadValues()请求接收FORM作为string响应,然后我必须提交 – 所以我不能使用第二个WebClient或HttpWebRequest。 这个请求返回了string。
using (WebClient client = new WebClient()) { byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection() { { "test", "value123" } }); result = System.Text.Encoding.UTF8.GetString(response); }
我可以用来解决OP问题的解决scheme是在代码末尾添加一个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)
我希望这可以帮助任何发现自己处于相同状况的人。
我需要一个button处理程序,在客户端的浏览器中创build一个表单发布到另一个应用程序。 我登陆这个问题,但没有看到一个适合我的情况的答案。 这就是我想到的:
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); }