请求地址 /// 请求头参数 /// 示例:入参: var dic = new Dictionary
当前位置:   article > 正文

C# Web Api Post 请求示例_c# webapi post 实例

c# webapi post 实例
  1. /// <summary>
  2. /// WEB-API,请求头方式调用
  3. /// </summary>
  4. /// <param name="requestUrl">请求地址</param>
  5. /// <param name="dicdata">请求头参数</param>
  6. /// 示例:入参: var dic = new Dictionary<string, string>();
  7. /// dic.Add("code", "RMIS");
  8. /// dic.Add("token", token);
  9. /// <returns>服务返回数据</returns>
  10. public static string RestPost(string requestUrl, Dictionary<string, string> dicdata)
  11. {
  12. Uri url = new Uri(requestUrl);
  13. // 创建webrequest
  14. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  15. request.Method = "POST";
  16. request.ContentType = "application/json";
  17. request.Timeout = 180000;
  18. //构建Header入参
  19. foreach (var item in dicdata)
  20. {
  21. request.Headers.Add(item.Key, item.Value);
  22. }
  23. try
  24. {
  25. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  26. {
  27. StreamReader reader = new StreamReader(response.GetResponseStream());
  28. return reader.ReadToEnd();
  29. }
  30. }
  31. catch (Exception e)
  32. {
  33. return e.Message;
  34. }
  35. }
  36. /// <summary>
  37. /// WEB-API调用
  38. /// </summary>
  39. /// <param name="requestUrl">请求地址</param>
  40. /// <param name="dicdata">请求头参数</param>
  41. /// 入参:var parm = "{\"key\":\"1011\",\"message\":\"<Request><Header></Header><Body></Body></Request>\"}";
  42. /// 后端接收代码:
  43. //[HttpPost]
  44. //public IHttpActionResult GetResult([FromBody] DataInfo data)
  45. //{
  46. // var result = new DataInfo { key = data.key, message = data.message };
  47. // return Json(result);
  48. //}
  49. /// <returns></returns>
  50. public static string HttpPost(string requestUrl, string body)
  51. {
  52. Uri url = new Uri(requestUrl);
  53. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  54. request.Method = "POST";
  55. request.Accept = "text/html, application/xhtml+xml, */*";
  56. request.ContentType = "application/json";
  57. request.Timeout = 180000;
  58. try
  59. {
  60. var encoding = Encoding.UTF8;
  61. byte[] buffer = encoding.GetBytes(body);
  62. request.ContentLength = buffer.Length;
  63. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  64. }
  65. catch (Exception e)
  66. {
  67. return e.Message;
  68. }
  69. try
  70. {
  71. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  72. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  73. {
  74. return reader.ReadToEnd();
  75. }
  76. }
  77. catch (Exception e)
  78. {
  79. return e.Message;
  80. }
  81. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/550447
推荐阅读
相关标签