1、经常遇到的问题
① 远程主机强迫关闭了一个现有的连接
相信大家在使用 HttpClient 的时候遇到过 远程主机强迫关闭了一个现有的连接 的错误,一般的解决方法就是下面这种
解决办法:在请求方法中指定 ServicePoint 安全协议
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
② POST请求某种情况下请求会失败的解决方案
工作中遇到写正常的 http post 请求会失败的问题,于是就在原有的基础上改动了写代码使用HttpRequestMessage 指定 标头、HTTP 谓词和潜在数据,详情见代码第二个 post 请求方法。
2、使用HttpClient为什么建议使用单例
HttpClient 旨在被实例化一次并在应用程序的整个生命周期中重复使用。为每个请求实例化一个 HttpClient 类将耗尽重负载下可用的套接字数量。将导致 SocketException 错误。
3、基础代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Text; namespace Clear.DataServices.HttpHelper { public class HttpClientService { private static HttpClientService _instance; private static readonly object _lock = new object(); private static HttpClient _client; public HttpClientService() { } public static HttpClientService GetInstance() { if (_instance == null) { lock (_lock) { if (_instance == null) { _instance = new HttpClientService(); } if (_client is null) { _client = new HttpClient(); } } } return _instance; } /// <summary> /// HttpClient Get请求 /// </summary> /// <param name="url">请求地址</param> /// <returns></returns> public string HttpGet(string url) { try { if (_client.BaseAddress is null) { _client.BaseAddress = new Uri(url); } client.DefaultRequestHeaders.Accept.Clear(); HttpResponseMessage response = client.GetAsync(url).Result; response.EnsureSuccessStatusCode(); string responseBody = response.Content.ReadAsStringAsync().Result; return responseBody; } catch (Exception e) { object errorMessage = new { code = "-1", message = e.Message }; return JsonConvert.SerializeObject(errorMessage); } } /// <summary> /// HttpClient Post请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="content">HttpContent</param> /// <returns></returns> public string HttpPost(string url, string content, string token = null) { try { if (_client.BaseAddress is null) { _client.BaseAddress = new Uri(url); } // System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Connection.Add("keep-alive"); if (!token.IsNullOrEmpty()) { client.DefaultRequestHeaders.Add("Authorization-Token", token); } client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json")).Result; response.EnsureSuccessStatusCode(); string responseBody = response.Content.ReadAsStringAsync().Result; return responseBody; } catch (Exception e) { object errorMessage = new { code = "-1", message = e.Message }; return JsonConvert.SerializeObject(errorMessage); } } /// <summary> /// HttpClient Post请求 /// </summary> /// <remarks> /// 用于非正常http请求 /// </remarks> /// <param name="url"></param> /// <param name="content"></param> /// <returns></returns> public string HttpPost(string url, string content) { try { using (var request = new HttpRequestMessage(new HttpMethod("Post"), url)) { // System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; request.Headers.TryAddWithoutValidation("Content-Type", "application/json"); request.Content = new StringContent(content); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var response = _client.SendAsync(request).Result; return response.Content.ReadAsStringAsync().Result; } } catch (Exception e) { object errorMessage = new { code = "-1", message = e.Message }; return JsonConvert.SerializeObject(errorMessage); } } /// <summary> /// Model对象转换为uri网址参数形式 /// </summary> /// <param name="obj">Model对象</param> /// <param name="url">前部分网址</param> /// <returns></returns> public string GetUriParam(object obj, string url = "") { PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); StringBuilder sb = new StringBuilder(); sb.Append(url); sb.Append("?"); foreach (var p in propertis) { var v = p.GetValue(obj, null); if (v == null) continue; sb.Append(p.Name); sb.Append("="); sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式,HttpUtility.UrlEncode是小写 sb.Append("&"); } sb.Remove(sb.Length - 1, 1); return sb.ToString(); } } } |