Skip to main content

HttpClientFactory

HttpClientFactory 提供 HTTP 客户端实例的创建能力,基于 IHttpClientFactory(ASP.NET Core 标准),用于在 C# 脚本或微服务中调用任意外部 HTTP 服务。

使用方式​

public IHttpClientFactory HttpClientFactory => serviceProvider.GetRequiredService<IHttpClientFactory>();

使用示例​

基本 GET 请求​

// 创建客户端并发起 GET 请求
var client = sdk.HttpClientFactory.CreateClient();
var response = await client.GetAsync("https://api.example.com/data");

response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();

带 JSON Body 的 POST 请求​

using var client = sdk.HttpClientFactory.CreateClient();

var payload = new { name = "test", value = 123 };
var json = JsonConvert.SerializeObject(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");

var response = await client.PostAsync("https://api.example.com/submit", content);
var result = await response.Content.ReadAsStringAsync();

命名客户端(带预配置)​

如果需要在微服务中复用相同配置的客户端,可通过依赖注入预先注册命名客户端:

// 使用命名客户端(需提前注册)
var client = sdk.HttpClientFactory.CreateClient("MyNamedClient");
var response = await client.GetAsync("https://my-api.example.com/endpoint");

设置超时和请求头​

var client = sdk.HttpClientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(30);

client.DefaultRequestHeaders.Add("Authorization", "Bearer your-token");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var response = await client.SendAsync(request);

典型场景​

调用第三方 Web API​

public async Task<object> ExecuteAsync(ComponentContext context, ChameleonSDK sdk)
{
var client = sdk.HttpClientFactory.CreateClient();

// 调用外部天气 API
var response = await client.GetAsync(
$"https://api.weather.com/current?city={cityName}&key={apiKey}");

var json = await response.Content.ReadAsStringAsync();
var weatherData = JsonConvert.DeserializeObject<WeatherResponse>(json);

return weatherData;
}

文件下载​

var client = sdk.HttpClientFactory.CreateClient();
var response = await client.GetAsync(fileUrl);

using var stream = await response.Content.ReadAsStreamAsync();
// 处理文件流...

注意事项​

  • IHttpClientFactory 管理 HttpClient 的生命周期,避免 socket 耗尽问题,不要自己 new HttpClient()
  • 对于调用平台内部的 OpenAPI,推荐使用 OpenApiHelper,它会自动处理认证
  • 对于微服务间调用主站内部接口,推荐使用 ServiceCallHelper
  • HttpClientFactory 主要适用于调用外部第三方服务的场景