如何使用C#提交http表单 [英] How to submit http form using C#

查看:35
本文介绍了如何使用C#提交http表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple html file such as

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

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

I may not have been clear enough with the question

我想编写 C# 代码,以与将上述 html 粘贴到文件中、使用 IE 打开并使用浏览器提交时完全相同的方式提交此表单.

I want to write C# code which submits this form in the exact same manner that would occur had I pasted the above html into a file, opened it with IE and submitted it with the browser.

推荐答案

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

Here is a sample script that I recently used in a Gateway POST transaction that receives a GET response. Are you using this in a custom C# form? Whatever your purpose, just replace the String fields (username, password, etc.) with the parameters from your form.

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#提交http表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆