1. Problems encountered
① The remote host forced an existing connection to close
I believe everyone encountered an error when using HttpClient. The remote host forced an existing connection to close. The general solution is the following
Solution: Specify the ServicePoint Security Protocol in the request method
= .Tls11 | .Tls12;
② A solution in which the request fails in a certain situation
During work, I encountered the problem that writing a normal http post request will fail, so I changed the code to use HttpRequestMessage to specify the header, HTTP predicate and potential data on the original basis. For details, see the second post request method in the code.
2. Why is it recommended to use single case using HttpClient
HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for each request will exhaust the number of available sockets under heavy load. Will cause a SocketException error.
3. Basic code implementation
using System; using ; using ; using ; using ; namespace { 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 Request /// </summary> /// <param name="url">Request address</param> /// <returns></returns> public string HttpGet(string url) { try { if (_client.BaseAddress is null) { _client.BaseAddress = new Uri(url); } (); HttpResponseMessage response = (url).Result; (); string responseBody = ().Result; return responseBody; } catch (Exception e) { object errorMessage = new { code = "-1", message = }; return (errorMessage); } } /// <summary> /// HttpClient Post request /// </summary> /// <param name="url">Request address</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); } // = .Tls11 | .Tls12; (); ("keep-alive"); if (!()) { ("Authorization-Token", token); } (new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = (url, new StringContent(content, Encoding.UTF8, "application/json")).Result; (); string responseBody = ().Result; return responseBody; } catch (Exception e) { object errorMessage = new { code = "-1", message = }; return (errorMessage); } } /// <summary> /// HttpClient Post request /// </summary> /// <remarks> /// for abnormal http requests /// </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)) { // = .Tls11 | .Tls12; ("Content-Type", "application/json"); = new StringContent(content); = ("application/json"); var response = _client.SendAsync(request).Result; return ().Result; } } catch (Exception e) { object errorMessage = new { code = "-1", message = }; return (errorMessage); } } /// <summary> /// Convert Model object to uri URL parameter form /// </summary> /// <param name="obj">Model object</param> /// <param name="url">Former URL</param> /// <returns></returns> public string GetUriParam(object obj, string url = "") { PropertyInfo[] propertis = ().GetProperties( | ); StringBuilder sb = new StringBuilder(); (url); ("?"); foreach (var p in propertis) { var v = (obj, null); if (v == null) continue; (); ("="); ((()));//Convert the string to its escape representation, which is lowercase ("&"); } ( - 1, 1); return (); } } }
This is the end of this article about the detailed explanation of the usage of HttpClient in C# and the solutions to related problems. For more related content of C# HttpClient, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!