遇到接口开发时,对接客户要求发送请求数据为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 = _appId18 });19 formDatas.Add(new FormItemModel()20 {21 Key = "ts",22 Values = _ts23 });24 formDatas.Add(new FormItemModel()25 {26 Key = "tokens",27 Value = _tokens28 });29 formDatas.Add(new FormItemModel()30 {31 Key = "Num",32 Value = _Num33 });34 formDatas.Add(new FormItemModel()35 {36 Key = "Code",37 Value = _Code38 });39 formDatas.Add(new FormItemModel()40 {41 Key = "idNo",42 Value = _idNo43 });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+"; 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
No comments:
Post a Comment