C# .net core HttpClientFactory 用法

C# .net core HttpClientFactory 用法
C# .net core HttpClient 优化

1,引入包

Microsoft.Extensions.Http

2,IOC注入

public void ConfigureServices(IServiceCollection services)
{
   services.AddHttpClient<IEmployeeService, 	  EmployeeService>(
                client => client.BaseAddress = new Uri("http://localhost:7000"));
            services.AddHttpClient<IDepartmentService, DepartmentService>(
                client => client.BaseAddress = new Uri("http://localhost:7000"));


    // 注入HttpClient
    services.AddHttpClient("client_1", config =>  //这里指定的name=client_1,可以方便我们后期服用该实例
    {
        config.BaseAddress = new Uri("http://www.baidu.com");
        config.DefaultRequestHeaders.Add("header_1", "header_1");
    });
    services.AddHttpClient("client_2", config =>
    {
        config.BaseAddress = new Uri("https://www.qq.com/");
        config.DefaultRequestHeaders.Add("header_2", "header_2");
    });
	
	

    services.AddHttpClient();

}

3使用

 public class DemoController : ControllerBase
    {
        IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 通过构造函数实现注入
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public DemoController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<string> Get()
        {
            var client = _httpClientFactory.CreateClient("client_1"); //复用在Startup中定义的client_1的httpclient
            var result = await client.GetStringAsync("/page1.html");

            var client2 = _httpClientFactory.CreateClient(); //新建一个HttpClient
            var result2 = await client.GetAsync("http://www.baidu.com");



            return result2.StatusCode.ToString();
        }
    }

4使用

public class EmployeeService: IEmployeeService
    {
        private readonly HttpClient _httpClient;

        public EmployeeService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<IEnumerable<EmployeeDto>> GetForDepartmentAsync(int departmentId)
        {
            return await JsonSerializer.DeserializeAsync<IEnumerable<EmployeeDto>>(
                await _httpClient.GetStreamAsync("api/department/1/employee"),
                new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
        }
}

5,HttpClient用法

get

  using var client = new HttpClient();
        var result = await client.GetAsync(url);

HEAD

  using var client = new HttpClient();
            var result = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));

post json

 var json = JsonConvert.SerializeObject(person);
            var data = new StringContent(json, Encoding.UTF8, "application/json");
            using (var client = new HttpClient()){
            //添加请求头
              client .DefaultRequestHeaders.Add("Authorization", "Bearer your_token");
        client .DefaultRequestHeaders.Add("User-Agent", "Your User Agent");

            var response = await client.PostAsync(url, data);
            string result = response.Content.ReadAsStringAsync().Result;
            }

post form

HttpContent postContent = new FormUrlEncodedContent(Dictionary);
	HttpResponseMessage response = await httpClient.PostAsync(requestUrl, postContent );
	response.EnsureSuccessStatusCode();
	responseBody = await response.Content.ReadAsStringAsync();

下载图片

 using var httpClient = new HttpClient();
            var url = "http://webcode.me/favicon.ico";
            byte[] imageBytes = await httpClient.GetByteArrayAsync(url);
            string documentsPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
            string localFilename = "favicon.ico";
            string localPath = Path.Combine(documentsPath, localFilename);
            File.WriteAllBytes(localPath, imageBytes);

post form-data上传文件

使用 HttpClient 发送 form-data 形式的请求来上传文件,可以按照以下步骤进行操作:
创建一个 HttpClient 实例:

HttpClient client = new HttpClient();

使用 MultipartFormDataContent 类创建一个 form-data 实例:

MultipartFormDataContent formData = new MultipartFormDataContent();

添加文件内容到 formData:

byte[] fileBytes = File.ReadAllBytes(filePath);
ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
formData.Add(fileContent, "file", "filename.ext");

这里的 “file” 是表单字段名,“filename.ext” 是上传文件的名称。

添加其他表单字段(可选):

formData.Add(new StringContent("value"), "field");

这里的 “field” 是表单字段名。

发送 POST 请求:

string url = "https://xxx.com/upload";
HttpResponseMessage response = await client.PostAsync(url, formData);

处理响应结果:

if (response.IsSuccessStatusCode)
{
    // 上传成功,处理逻辑
}
else
{
    // 处理错误情况
}
 public async Task UploadFile(string filePath)
    {
        using (HttpClient client = new HttpClient())
        {
            using (MultipartFormDataContent formData = new MultipartFormDataContent())
            {
                byte[] fileBytes = File.ReadAllBytes(filePath);
                ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
                formData.Add(fileContent, "file", Path.GetFileName(filePath));

                // 添加其他表单字段
                formData.Add(new StringContent("value"), "field");

                string url = "https://example.com/upload";
                HttpResponseMessage response = await client.PostAsync(url, formData);

                if (response.IsSuccessStatusCode)
                {
                    // 上传成功,处理逻辑
                }
                else
                {
                    // 处理错误情况
                }
            }
        }
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值