程序地带

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 " --" + boundary +
37 " Content-Disposition: form-data; name="{0}"; filename="{1}"" +
38 " Content-Type: application/octet-stream" +
39 " ";
40 //文本数据模板
41 string dataFormdataTemplate =
42 " --" + boundary +
43 " Content-Disposition: form-data; name="{0}"" +
44 " {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(" --" + boundary + "-- ");
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 }

 


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/songming513/p/14228432.html

随机推荐

Umi3(Umi)

Umi是什么?Umi,中文可发音为乌米,是可扩展的企业级前端应用框架。Umi以路由为基础的,同时支持配置式路由和约定式路由,保证路...

An_s 阅读(251)

uniapp 子组件 props拿不到数据_vue组件

vue组件1、创建vue组件建组件的方式有两种,一种是局部组件,一种是全局组件1.1局部组件介绍​通过对象的方式创建了一个组件,由对象的template属性指...

weixin_39954889 阅读(462)

【Unity笔记】IEnumerator协程的用法

协程一般用于实现需要间隔一定的时间调用方法,比如将一个游戏对象移动至某一点,如果直接用transform.translate(pos),那么这个行为会在一帧之...

反抗的人 阅读(534)

babylonJs 水材质

babylonJs水材质babylonjs3.0(及以上提供了水材质),我们可以通过代码实现特别好看的水材质.需要单独导入特殊材质文件,materials.js(最后会提供源代码)<script...

杨一鸣d 阅读(620)

Java界面开发

Java界面开发界面开发代码的实现创建一个==窗口==设置好==布局==:加载各种==按钮=...

江中~ 阅读(762)

删除留言板功能 2020/11/22

node.removeChild(child);删除的是li当前a所在的lithis.parentNode;javascrip:;阻止链接跳转需要添加Javascript:void(0);或者java...

【5】吴润泽 阅读(708)

观雪有感

观雪文/纳兰青枫         朝逢曙雀焰,夜遇玉龙寒。生平居九霄,何故恋凡间?庚子鼠年丁亥月戊辰日                         ...

Eric_Yeung 阅读(407)

python自动化笔记(四)—— 模块/包导入

一、什么是模块?一个以.py结尾的文件就是一个python模块二、什么是包?一个包含__init__.py的文件夹,为一个python包三、模块和包导入1内置...

Py小迷哥 阅读(509)