保持使用全局 HttpClient,但确保不同请求的 HttpRequestMessage 独立
这是推荐的最佳实践,因为 HttpClient 是设计为可重用的,你可以使用独立的 HttpRequestMessage 来确保每个请求有独立的请求头,而不影响其他请求。
private static readonly HttpClient client = new HttpClient(); var str = JsonConvert.SerializeObject(vo); var content = new StringContent(str, Encoding.UTF8, "application/json"); using (var request = new HttpRequestMessage(HttpMethod.Post, site.Url)) { request.Content = content; request.Headers.Add("appUserKey", appUserKey); request.Headers.Add("nonce", nonce); request.Headers.Add("timestamp", timestampStr); request.Headers.Add("sign", signature); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; LogHelper.Info($"{DateTime.Now}: PostAsync {site.Name}({site.Url})"); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { LogHelper.Info($"{DateTime.Now}: 推送数接口返回 {site.Name}({site.Url}) ({await response.Content.ReadAsStringAsync()})"); } else { LogHelper.Info($"{DateTime.Now}: 推送数据出错 {site.Name}({site.Url}) , 状态码: {response.StatusCode}"); } }
标签:HttpRequestMessage,request,site,Add,var,全局,HttpClient From: https://www.cnblogs.com/0banana0/p/18412237