C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据 gzip压缩_c# 解压缩response gzip

在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求
在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求 6.0

Net 热门 HTTP 开源库
1、Flurl
2、FluentHttpClient
3、RestSharp

HttpWebRequest【.NET早期版本,同步方式】
WebClient【HttpWebRequest的封装简化版,同步方式】
HttpClient    【.NET4.5以后,异步方式】
HttpClientFactory【.NET Core2.1】

获取当前时间、获取 WebHeaderCollection 参数

  1. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  2. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  3. //方式一:获取当前时间
  4. var lastModified = response.LastModified;
  5. WebHeaderCollection headerCollection = response.Headers;
  6. foreach (var h in headerCollection.AllKeys)
  7. {
  8. if (h == "Date")
  9. {
  10. //方式二:获取当前时间
  11. var datetime = headerCollection[h];
  12. DateTime time = GMT2Local(headerCollection[h]);
  13. }
  14. }
  15. /// <summary>
  16. /// GMT时间转成本地时间
  17. /// Fri, 18 Mar 2022 13:55:32 GMT
  18. /// </summary>
  19. /// <param name="gmt">字符串形式的GMT时间</param>
  20. /// <returns></returns>
  21. public DateTime GMT2Local(string gmt)
  22. {
  23. DateTime dt = DateTime.MinValue;
  24. try
  25. {
  26. string pattern = "";
  27. if (gmt.IndexOf("+0") != -1)
  28. {
  29. gmt = gmt.Replace("GMT", "");
  30. pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
  31. }
  32. if (gmt.ToUpper().IndexOf("GMT") != -1)
  33. {
  34. pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
  35. }
  36. if (pattern != "")
  37. {
  38. dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
  39. dt = dt.ToLocalTime();
  40. }
  41. else
  42. {
  43. dt = Convert.ToDateTime(gmt);
  44. }
  45. }
  46. catch
  47. {
  48. }
  49. return dt;
  50. }

*

  1. /// <summary>
  2. /// 日期:2016-2-4
  3. /// 备注:bug已修改,可以使用
  4. /// </summary>
  5. public static void Method1()
  6. {
  7.     try
  8.     {
  9.         string domain = "http://192.168.1.6:8098/";
  10.         string url = domain + "/Signin/LoginApi";
  11.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  12.         request.Method = "POST";
  13.         request.ContentType = "application/x-www-form-urlencoded";
  14. //request.ContentType = "application/json";
  15.         request.ReadWriteTimeout = 30 * 1000;
  16. // 忽略证书
  17. request.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
  18. return true;
  19. };
  20.         ///添加参数
  21.         Dictionary<String, String> dicList = new Dictionary<String, String>();
  22.         dicList.Add("UserName", "test@qq.com");
  23.         dicList.Add("Password", "000000");
  24.         String postStr = buildQueryStr(dicList);
  25.         byte[] data = Encoding.UTF8.GetBytes(postStr);
  26.         request.ContentLength = data.Length;
  27.         Stream myRequestStream = request.GetRequestStream();
  28.         myRequestStream.Write(data, 0, data.Length);
  29.         myRequestStream.Close();
  30.         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  31. //当前时间
  32. var lastModified = response.LastModified;
  33. WebHeaderCollection headerCollection = response.Headers;
  34. foreach (var h in headerCollection.AllKeys)
  35. {
  36. if (h == "Date")
  37. {
  38. var datetime = headerCollection[h];
  39. DateTime time = GMT2Local(headerCollection[h]);
  40. }
  41. }
  42.         StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  43.         var retString = myStreamReader.ReadToEnd();
  44.         myStreamReader.Close();
  45.     }
  46.     catch (Exception ex)
  47.     {
  48.         log.Info("Entered ItemHierarchyController - Initialize");
  49.         log.Error(ex.Message);
  50.     }
  51. }
  52. /// <summary>
  53. /// GMT时间转成本地时间
  54. /// Fri, 18 Mar 2022 13:55:32 GMT
  55. /// </summary>
  56. /// <param name="gmt">字符串形式的GMT时间</param>
  57. /// <returns></returns>
  58. public DateTime GMT2Local(string gmt)
  59. {
  60. DateTime dt = DateTime.MinValue;
  61. try
  62. {
  63. string pattern = "";
  64. if (gmt.IndexOf("+0") != -1)
  65. {
  66. gmt = gmt.Replace("GMT", "");
  67. pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
  68. }
  69. if (gmt.ToUpper().IndexOf("GMT") != -1)
  70. {
  71. pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
  72. }
  73. if (pattern != "")
  74. {
  75. dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
  76. dt = dt.ToLocalTime();
  77. }
  78. else
  79. {
  80. dt = Convert.ToDateTime(gmt);
  81. }
  82. }
  83. catch
  84. {
  85. }
  86. return dt;
  87. }

升级版本,提取到帮助类,封装对象,gzip压缩

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Web;
  8. namespace CMS.Common
  9. {
  10. public class MyHttpClient
  11. {
  12. public string methodUrl = string.Empty;
  13. public string postStr = null;
  14. public MyHttpClient(String methodUrl)
  15. {
  16. this.methodUrl = methodUrl;
  17. }
  18. public MyHttpClient(String methodUrl, String postStr)
  19. {
  20. ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi
  21. ///this.postStr = postStr;
  22. this.methodUrl = methodUrl;
  23. this.postStr = postStr;
  24. }
  25. /// <summary>
  26. /// GET Method
  27. /// </summary>
  28. /// <returns></returns>
  29. public String ExecuteGet()
  30. {
  31. HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);
  32. myRequest.Method = "GET";
  33. myRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");
  34. // 忽略证书
  35. myRequest.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
  36. return true;
  37. };
  38. HttpWebResponse myResponse = null;
  39. try
  40. {
  41. myResponse = (HttpWebResponse)myRequest.GetResponse();
  42. StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
  43. StreamReader reader = new StreamReader(new GZipStream(myResponse.GetResponseStream(), CompressionMode.Decompress), Encoding.GetEncoding("utf-8"));
  44. string content = reader.ReadToEnd();
  45. return content;
  46. }
  47. //异常请求
  48. catch (WebException e)
  49. {
  50. myResponse = (HttpWebResponse)e.Response;
  51. using (Stream errData = myResponse.GetResponseStream())
  52. {
  53. using (StreamReader reader = new StreamReader(errData))
  54. {
  55. string text = reader.ReadToEnd();
  56. return text;
  57. }
  58. }
  59. }
  60. }
  61. /// <summary>
  62. /// POST Method
  63. /// </summary>
  64. /// <returns></returns>
  65. public string ExecutePost()
  66. {
  67. string content = string.Empty;
  68. Random rd = new Random();
  69. int rd_i = rd.Next();
  70. String nonce = Convert.ToString(rd_i);
  71. String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
  72. String signature = GetHash(this.appSecret + nonce + timestamp);
  73. try
  74. {
  75. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);
  76. request.Method = "POST";
  77. request.ContentType = "application/x-www-form-urlencoded";
  78. //request.ContentType = "application/json";
  79. request.Headers.Add("Nonce", nonce);
  80. request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));
  81. request.Headers.Add("Signature", signature);
  82. request.ReadWriteTimeout = 30 * 1000;
  83. // 忽略证书
  84. request.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
  85. return true;
  86. };
  87. byte[] data = Encoding.UTF8.GetBytes(postStr);
  88. request.ContentLength = data.Length;
  89. Stream myRequestStream = request.GetRequestStream();
  90. myRequestStream.Write(data, 0, data.Length);
  91. myRequestStream.Close();
  92. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  93. StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  94. content = myStreamReader.ReadToEnd();
  95. myStreamReader.Close();
  96. }
  97. catch (Exception ex)
  98. {
  99. }
  100. return content;
  101. }
  102. /// <summary>
  103. /// POST Method 调用示例
  104. /// Dictionary<string, string> parm = new Dictionary<string, string>();
  105. /// parm.Add("user_name", "admin");
  106. /// parm.Add("password", "123456");
  107. /// var result = ExecutePost("http://******:9000/api/v1/passport/login", JsonConvert.SerializeObject(parm));
  108. /// </summary>
  109. /// <returns></returns>
  110. public string ExecutePost(string url, string data)
  111. {
  112. byte[] buffer = Encoding.UTF8.GetBytes(data);
  113. HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
  114. myRequest.Method = "POST";
  115. myRequest.ContentType = "application/json";
  116. myRequest.ContentLength = buffer.Length;
  117. // 忽略证书
  118. myRequest.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
  119. return true;
  120. };
  121. Stream newStream = myRequest.GetRequestStream();
  122. newStream.Write(buffer, 0, buffer.Length);
  123. newStream.Close();
  124. HttpWebResponse myResponse = null;
  125. try
  126. {
  127. myResponse = (HttpWebResponse)myRequest.GetResponse();
  128. StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
  129. string content = reader.ReadToEnd();
  130. return content;
  131. }
  132. //异常请求
  133. catch (WebException e)
  134. {
  135. myResponse = (HttpWebResponse)e.Response;
  136. using (Stream errData = myResponse.GetResponseStream())
  137. {
  138. using (StreamReader reader = new StreamReader(errData))
  139. {
  140. string text = reader.ReadToEnd();
  141. LogUtils.GetInstance().Info($"Ln 152 {text}");
  142. return text;
  143. }
  144. }
  145. }
  146. }
  147. }
  148. public class StringProc
  149. {
  150. public static String buildQueryStr(Dictionary<String, String> dicList)
  151. {
  152. String postStr = "";
  153. foreach (var item in dicList)
  154. {
  155. postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
  156. }
  157. postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
  158. return postStr;
  159. }
  160. public static int ConvertDateTimeInt(System.DateTime time)
  161. {
  162. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
  163. return (int)(time - startTime).TotalSeconds;
  164. }
  165. }
  166. }

前端调用

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using CMS.Common;
  7. using Newtonsoft.Json;
  8. namespace Medicine.Web.Controllers
  9. {
  10. public class DefaultController : Controller
  11. {
  12. public ActionResult Index()
  13. {
  14. #region DoGet
  15. string getResultJson = this.DoGet(url);
  16. HttpClientResult customerResult = (HttpClientResult)JsonConvert.DeserializeObject(getResultJson, typeof(HttpClientResult));
  17. #endregion
  18. #region DoPost
  19. string name = Request.Form["UserName"];
  20. string password = Request.Form["Password"];
  21. Dictionary<String, String> dicList = new Dictionary<String, String>();
  22. dicList.Add("UserName", name);
  23. dicList.Add("Password", password);
  24. string postStr = StringProc.buildQueryStr(dicList);
  25. string postResultJson = this.DoPost(url, postStr);
  26. HttpClientResult userResult = (HttpClientResult)JsonConvert.DeserializeObject(postResultJson, typeof(HttpClientResult));
  27. #endregion
  28. return View();
  29. }
  30. /// <summary>
  31. /// GET Method
  32. /// </summary>
  33. /// <param name="portraitUri">url地址</param>
  34. /// <returns></returns>
  35. private String DoGet(string portraitUri)
  36. {
  37. MyHttpClient client = new MyHttpClient(portraitUri);
  38. return client.ExecuteGet();
  39. }
  40. /// <summary>
  41. /// POST Method
  42. /// </summary>
  43. /// <param name="portraitUri">url地址</param>
  44. /// <param name="postStr">请求参数</param>
  45. /// <returns></returns>
  46. private String DoPost(string portraitUri, string postStr)
  47. {
  48. MyHttpClient client = new MyHttpClient(portraitUri, postStr);
  49. return client.ExecutePost();
  50. }
  51. public class HttpClientResult
  52. {
  53. public string UserName { get; set; }
  54. public bool Success { get; set; }
  55. }
  56. }
  57. }

HttpClient

  1. var responseString = string.Empty;
  2. using (var client = new HttpClient())
  3. {
  4. var values = new Dictionary<string, string>
  5. {
  6. { "apikey", apiKey },
  7. { "mobile", phoneNumber },
  8. { "text", smsMessage }
  9. };
  10. var content = new FormUrlEncodedContent(values);
  11. var response = await client.PostAsync(url, content);
  12. responseString = await response.Content.ReadAsStringAsync();
  13. }

.net framework 3.5 版本,遇见“基础连接已关闭”的问题,尝试如下方法:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

微软官方文档说明:SecurityProtocolType 枚举 (System.Net) | Microsoft Docs

忽略证书
myRequest.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
    return true;
}