.NetCore【工作应用】HttpClient
IHttpClientFactory
在项目中经常有遇到调用第三方接口的情况,一般我们使用HttpClient
来请求调用第三方接口,.net core 中可以使用HttpClientFactory
来管理HttpClient
直接使用IHttpClientFactory
先注册服务
public void ConfigureServices(IServiceCollection services)
{
//HttpClient
services.AddHttpClient();
}
之后在控制器中使用
public class ThirdRequestController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public ThirdRequestController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<ActionResult> Get()
{
var client = _httpClientFactory.CreateClient();
string result = await client.GetStringAsync("/");
return Ok(result);
}
}
通过HttpClient
名字生成HttpClient
实际在工作使用中,我们经常需要对第三方的接口进行调用,而第三方的请求一般都会加上一下特定的请求头,例如token
,不想在每个请求时都代码加上token,可以包装出一个Client出来
注册时可以添加有一个name
的HttpClient
services.AddHttpClient();
services.AddHttpClient("github", c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});
使用时,根据name
获取对应的HttpClient
var client = _httpClientFactory.CreateClient("github");
使用自定义HttpClient生成
觉得这么多代码写在注册代码不方便,而且有很多第三方接口时,代码也很混乱,可以把每个HttpClient
封装一下
public class GitHubClient
{
public HttpClient Client { get; private set; }
public GitHubClient(HttpClient httpClient)
{
httpClient.BaseAddress = new Uri("https://api.github.com/");
httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
Client = httpClient;
}
}
// 注册时
services.AddHttpClient<GitHubClient>();
// 控制器中使用
public class ValuesController : Controller
{
private readonly GitHubClient _gitHubClient;;
public ValuesController(GitHubClient gitHubClient)
{
_gitHubClient = gitHubClient;
}
[HttpGet]
public async Task<ActionResult> Get()
{
string result = await _gitHubClient.client.GetStringAsync("/");
return Ok(result);
}
}
将调用方法也放在自定义HttpClient中
调用第三方接口时可能不止一个请求接口,写在不同的地方很混乱,就想着把他们都放在这个GitHubClient
中
public interface IGitHubClient
{
Task<string> GetData();
}
public class GitHubClient : IGitHubClient
{
private readonly HttpClient _client;
public GitHubClient(HttpClient httpClient)
{
httpClient.BaseAddress = new Uri("https://api.github.com/");
httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
_client = httpClient;
}
public async Task<string> GetData()
{
return await _client.GetStringAsync("/");
}
}
// 注册服务
services.AddHttpClient<IGitHubClient, GitHubClient>();
// 使用时
string result = await _gitHubClient.GetData();