欢迎光临
我的个人博客网站

c#关于 做接口开发时,遇到的Form表单提交数据

遇到接口开发时,对接客户要求发送请求数据为form表单提交,以下是经过大佬们写过类似整理出来适合我自己用的一套

 public class FormItemModel     {         /// <summary>         ///主键         /// </summary>         public string Key { set; get; }         /// <summary>         ////// </summary>         public string Value { set; get; }         /// <summary>         ////// </summary>         public long Values { get; set; }     }

 1 private void btn_Click(object sender, EventArgs e)  2 {  4 var url = "*******************************";  5 long _ts = ConvertDataTimeToLong(DateTime.Now);  6 string _appSecret = "*************";  7 string _appId = "****************";  8 string _tokens = "";//加密  9 string _Num = "123"; 10 string _Code = "111"; 11 string _idNo = "1111"; 12 var formDatas = new List<FormItemModel>(); 13  14 formDatas.Add(new FormItemModel() 15 { 16 Key = "appId", 17 Value = _appId 18 }); 19 formDatas.Add(new FormItemModel() 20 { 21 Key = "ts", 22 Values = _ts 23 }); 24 formDatas.Add(new FormItemModel() 25 { 26 Key = "tokens", 27 Value = _tokens 28 }); 29 formDatas.Add(new FormItemModel() 30 { 31 Key = "Num", 32 Value = _Num 33 }); 34 formDatas.Add(new FormItemModel() 35 { 36 Key = "Code", 37 Value = _Code 38 }); 39 formDatas.Add(new FormItemModel() 40 { 41 Key = "idNo", 42 Value = _idNo 43 }); 44 //提交表单 45 var result = HTExamDocking.PostForm(url, formDatas); 46 if (result != null) 47 { 48 //MessageBox.Show("成功"); 49 } 50 }

  1  /// <summary>   2         /// 使用Post方法获取字符串结果   3         /// </summary>   4         /// <param name="url"></param>   5         /// <param name="formItems">Post表单内容</param>   6         /// <param name="cookieContainer"></param>   7         /// <param name="timeOut">默认20秒</param>   8         /// <param name="encoding">响应内容的编码类型(默认utf-8)</param>   9         /// <returns></returns>  10         public static string PostForm(string url, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)  11         {  12             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  13             #region 初始化请求对象  14             request.Method = "POST";  15             request.Timeout = timeOut;  16             request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";  17             request.KeepAlive = true;  18             request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";  19             if (!string.IsNullOrEmpty(refererUrl))  20                 request.Referer = refererUrl;  21             if (cookieContainer != null)  22                 request.CookieContainer = cookieContainer;  23             #endregion  24   25             string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符  26             request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);  27             //请求流  28             var postStream = new MemoryStream();  29             #region 处理Form表单请求内容  30             //是否用Form上传文件  31             var formUploadFile = formItems != null && formItems.Count > 0;  32             if (formUploadFile)  33             {  34                 //文件数据模板  35                 string fileFormdataTemplate =  36                     "rn--" + boundary +  37                     "rnContent-Disposition: form-data; name="{0}"; filename="{1}"" +  38                     "rnContent-Type: application/octet-stream" +  39                     "rnrn";  40                 //文本数据模板  41                 string dataFormdataTemplate =  42                     "rn--" + boundary +  43                     "rnContent-Disposition: form-data; name="{0}"" +  44                     "rnrn{1}";  45                 foreach (var item in formItems)  46                 {  47                     string formdata = null;  48   49                     //上传文本  50                     if (item.Value != null)  51                     {  52                         formdata = string.Format(  53                         dataFormdataTemplate,  54                         item.Key,  55                         item.Value);  56                     }  57                     else  58                     {  59                         formdata = string.Format(  60                         dataFormdataTemplate,  61                         item.Key,  62                         item.Values);  63                     }  64                     //统一处理  65                     byte[] formdataBytes = null;  66                     //第一行不需要换行  67                     if (postStream.Length == 0)  68                         formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));  69                     else  70                         formdataBytes = Encoding.UTF8.GetBytes(formdata);  71                     postStream.Write(formdataBytes, 0, formdataBytes.Length);  72                 }  73                 //结尾  74                 var footer = Encoding.UTF8.GetBytes("rn--" + boundary + "--rn");  75                 postStream.Write(footer, 0, footer.Length);  76   77             }  78             else  79             {  80                 request.ContentType = "application/x-www-form-urlencoded";  81             }  82             #endregion  83   84             request.ContentLength = postStream.Length;  85   86             #region 输入二进制流  87             if (postStream != null)  88             {  89                 postStream.Position = 0;  90                 //直接写入流  91                 Stream requestStream = request.GetRequestStream();  92   93                 byte[] buffer = new byte[1024];  94                 int bytesRead = 0;  95                 while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)  96                 {  97                     requestStream.Write(buffer, 0, bytesRead);  98                 }  99  100                 ////debug 101                 //postStream.Seek(0, SeekOrigin.Begin); 102                 //StreamReader sr = new StreamReader(postStream); 103                 //var postStr = sr.ReadToEnd(); 104                 postStream.Close();//关闭文件访问 105             } 106             #endregion 107  108             HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 109             if (cookieContainer != null) 110             { 111                 response.Cookies = cookieContainer.GetCookies(response.ResponseUri); 112             } 113  114             using (Stream responseStream = response.GetResponseStream()) 115             { 116                 using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8)) 117                 { 118                     string retString = myStreamReader.ReadToEnd(); 119                     return retString; 120                 } 121             } 122         }

 

赞(0) 打赏
未经允许不得转载:张拓的天空 » c#关于 做接口开发时,遇到的Form表单提交数据
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏