c# 模拟post请求 键值对方式

c# 模拟post请求  键值对方式

引用

using System.Collections.Generic;

using System.Net.Http;

#region Post请求 
        /// <summary>
        ///  psot请求 key-value 
        /// </summary>
        /// <param name="url">请求连接</param>
        /// <param name="parms">请求参数 字典类型</param>
        /// <param name="statusCode">请求状态码</param>
        /// <returns></returns>
        public string HttpPost(string url, Dictionary<string, string> parms, out string statusCode)
        {
            try
            {
                string result = string.Empty;
                //设置Http的正文
                FormUrlEncodedContent httpContent = new FormUrlEncodedContent(parms);

                using (HttpClient httpClient = new HttpClient())
                {
                    //异步Post
                    HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                    //输出Http响应状态码
                    statusCode = response.StatusCode.ToString();
                    //确保Http响应成功
                    if (response.IsSuccessStatusCode)
                    {
                        //异步读取json
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                }
                return result;
            }
            catch (HttpRequestException e)
            {
                statusCode = "An error occurred in this request";
                return e.Message;
            }
        }
        #endregion

 

添加数据及使用

#region 请求key-value 字典
     Dictionary<string, string> da = new Dictionary<string, string>();                    
     da.Add("key1", "value1");
   da.Add("key2", "value2");
     //使用
   string statusCode = string.Empty;//请求的状态
     string result = HttpPost("http://pay.attractpay.co.nz/online/H5PayTest", da, out statusCode);

 

c# 模拟post请求 键值对方式

上一篇:.net core webapi的参数设置


下一篇:WinCMD mode命令 - 显示系统状态、更改系统设置或重新配置端口或设备