C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# .net core HttpClientFactory用法

C# .net core HttpClientFactory用法及说明

作者:zxb11c

这篇文章主要介绍了C# .net core HttpClientFactory用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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();
        }
    }
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
                });
        }
}

4.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
                {
                    // 处理错误情况
                }
            }
        }
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文