当前位置:   article > 正文

C# HttpWebRequest调用WebAPI接口_c# httpwebrequest调用webapi接口传输对象序列化后字符串

c# httpwebrequest调用webapi接口传输对象序列化后字符串
  1. //设置request参数(新建实体类)
  2. HttpDataCenterSearchRequest requestData = new HttpDataCenterSearchRequest();
  3. requestData.clientId = clientId;
  4. requestData.currentPage = 0;
  5. requestData.signature = StrResult;
  6. requestData.sql = sql;
  7. requestData.timestamp = timestamp;
  8. //将实体类序列化
  9. var requestJson = JsonConvert.SerializeObject(requestData);
  10. //调用WebApi
  11. var res = PostUrl(url, requestJson);
  12. if (!string.IsNullOrEmpty(res))
  13. {
  14. //将返回的res进行反序列化(得到实体类)
  15. var response = JsonConvert.DeserializeObject<HttpDataCenterSearchResponse>(res);
  16. if (response != null)
  17. {
  18. //赋值
  19. }
  20. }
  21. //调用WebApi请求类
  22. public string PostUrl(string url, string postData)
  23. {
  24. try
  25. {
  26. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  27. //跳过证书校验(调用https请求时使用)
  28. req.ServerCertificateValidationCallback = (_s, _x509s, _x509c, _ssl) => { return (true); };
  29. req.Method = "POST";
  30. //req.Timeout = 800;//设置请求超时时间,单位为毫秒
  31. req.ContentType = "application/json";
  32. byte[] data = Encoding.UTF8.GetBytes(postData);
  33. req.ContentLength = data.Length;
  34. using (Stream reqStream = req.GetRequestStream())
  35. {
  36. reqStream.Write(data, 0, data.Length);
  37. reqStream.Close();
  38. }
  39. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  40. Stream stream = resp.GetResponseStream();
  41. //获取响应内容
  42. string result = "";
  43. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  44. {
  45. result = reader.ReadToEnd();
  46. }
  47. return result;
  48. }
  49. catch (Exception ex)
  50. {
  51. MessageBox.Show("WebApi接口调用失败:" + ex.Message);
  52. return "";
  53. }
  54. }

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

闽ICP备14008679号