c# - 如何使用C#提交http表单

标签 c# .net html forms http-post

我有一个简单的 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# 表单中使用它?无论您的目的是什么,只需将字符串字段(用户名、密码等)替换为表单中的参数即可。

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

关于c# - 如何使用C#提交http表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39860667/

相关文章:

c# - 动态中的值类型运算符处理是否存在错误?

.net - 在 azure 代理中运行 nunit 测试时找不到 testhost.deps.json 文件

android - GCM 推送通知导致 502 Bad Gateway

javascript - 点击事件的问题

javascript - 同步多个带有惯性效果的滚动div

C# - 定期读取文件最后一部分的最有效方法

c# - 在 MySQL 中插入查询后获取自动增量值

c# - 制作 NxN tic tac toe GUI wpf c#

c# - 问题: Failed to load viewstate

html - 如何在纯 CSS 中创建视差效果?