控制台发起http请求
class Program { static string url = "http://localhost:56157/"; //接口地址 static string method = string.Empty; //接口方法 static void Main(string[] args) { string key = "T8951SLI02UTY983CVBAX03"; //接口的授权Key Dictionary<string, string> pars = new Dictionary<string, string>(); //参数 //请求接口 // ①创建查询参数Json对象 Console.WriteLine("创建接口查询参数..."); var dataJson = JsonHelper.ObjectConvertJson(new { ID = "10001" }); // ②获取此次请求签名 Console.WriteLine("开始获取签名..."); CommResponse<string> sign = getApiSign("Query", dataJson); if (sign.Code == 1) { Console.WriteLine("签名获取成功:" + sign.Data); //获取签名成功则继续请求数据接口 // ③创建签名Json var signJson = JsonHelper.ObjectConvertJson(new { Key = key, Sign = sign.Data, Type = "Query" }); // ④封装参数开始请求 pars.Add("param", signJson); pars.Add("json", dataJson); method = "queryUser"; Console.WriteLine("开始发起查询请求..."); string result = Http.SendRequest(url + method, pars); Console.WriteLine("请求结果:" + result); } else { //获取签名失败 Console.WriteLine("签名获取失败:" + sign.Message); } Console.ReadKey(); } /// <summary> /// 获取请求签名 /// </summary> /// <param name="type">操作类型</param> /// <param name="data">要请求的数据</param> /// <returns></returns> public static CommResponse<string> getApiSign(string type, string data) { Dictionary<string, string> pars = new Dictionary<string, string>(); //参数 string key = "T8951SLI02UTY983CVBAX03"; //接口的授权Key method = "getSign"; pars.Add("key", key); pars.Add("type", type); pars.Add("data", data); string result = Http.SendRequest(url + method, pars); if (!string.IsNullOrWhiteSpace(result)) { return JsonHelper.JsonConvertObject<CommResponse<string>>(result); } else { return new CommResponse<string>() { Code = 2, Message = "获取失败" }; } } }
http帮助类:
public class Http { /// <summary> /// 发起请求 /// </summary> /// <param name="url">接口地址</param> /// <param name="pars">字典类型的参数集合</param> /// <param name="timeout"></param> /// <returns></returns> public static string SendRequest(string url, IDictionary<string, string> pars, int timeout = 120) { HttpWebRequest request = CreateRequest(url); byte[] pdata = Encoding.UTF8.GetBytes(BuildQuery(pars, "utf-8")); request.ContentLength = pdata.Length; Stream writer = null; try { writer = request.GetRequestStream(); } catch (Exception ex) { return ex.Message; } writer.Write(pdata, 0, pdata.Length); writer.Close(); HttpWebResponse response = null; try { //获得响应流 response = (HttpWebResponse)request.GetResponse(); } catch (Exception ex) { return ex.Message; } StreamReader sRead = new StreamReader(response.GetResponseStream()); string postContent = sRead.ReadToEnd(); sRead.Close(); return postContent; } /// <summary> /// 创建一个Http请求 /// </summary> /// <param name="url">接口地址</param> /// <param name="timeout">超时时间:秒</param> /// <returns></returns> public static HttpWebRequest CreateRequest(string url, int timeout = 30) { HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(url); mRequest.Proxy = null; mRequest.UseDefaultCredentials = false; mRequest.AllowWriteStreamBuffering = true; mRequest.Headers[HttpRequestHeader.AcceptLanguage] = "zh-CN"; mRequest.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate"; mRequest.Headers[HttpRequestHeader.CacheControl] = "no-cache"; mRequest.Accept = "*/*"; mRequest.Method = "POST"; mRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; mRequest.ProtocolVersion = HttpVersion.Version11; mRequest.ServicePoint.Expect100Continue = false; mRequest.ServicePoint.ConnectionLimit = 20000; mRequest.ServicePoint.MaxIdleTime = 20000; mRequest.ServicePoint.ReceiveBufferSize = 16384; mRequest.PreAuthenticate = true; mRequest.AllowAutoRedirect = false; mRequest.Timeout = timeout * 1000; mRequest.ReadWriteTimeout = timeout * 1000; mRequest.KeepAlive = true; return mRequest; } /// <summary> /// 组装普通文本请求参数。 /// </summary> /// <param name="parameters">Key-Value形式请求参数字典</param> /// <returns>URL编码后的请求数据</returns> static string BuildQuery(IDictionary<string, string> parameters, string encode) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略参数名或参数值为空的参数 if (!string.IsNullOrEmpty(name)) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); if (encode == "gb2312") { postData.Append(System.Web.HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312"))); } else if (encode == "utf8") { postData.Append(System.Web.HttpUtility.UrlEncode(value, Encoding.UTF8)); } else { postData.Append(value); } hasParam = true; } } return postData.ToString(); } }
--来源:C# Nancy框架开发 WebApi 二:接口安全签名认证 - 阿东呢 - 博客园 (cnblogs.com)