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

1.可以通过调用 AddHttpClient 来注册 IHttpClientFactory

引用:Microsoft.Extensions.Http

模块中添加 services.AddHttpClient();

2.如下代码请求

private readonly IHttpClientFactory _clientFactory;
public SmsAppSevice(IHttpClientFactory clientFactory)
{
  _clientFactory =clientFactory;
}

 

public void HttpClientPost(string url, string requestJson)
{
   Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  Uri postUrl = new Uri(url);
  var encodeBytes = Encoding.GetEncoding("GB2312").GetBytes(requestJson);
  using (HttpContent httpContent = new ByteArrayContent(encodeBytes))
  //using (HttpContent httpContent = new StringContent(encodeBytes))
  {
  httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  var client1 = _clientFactory.CreateClient();
  client1.Timeout = new TimeSpan(0, 0, 60);
  var result = client1.PostAsync(postUrl, httpContent).Result.Content.ReadAsStringAsync().Result;

  }
}

 

posted @ 2021-04-11 15:35  北极星下落不明  阅读(764)  评论(0编辑  收藏  举报