欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# .net core HttpClientFactory用法及說明

 更新時間:2023年11月07日 14:20:45   作者: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>
        /// 通過構(gòu)造函數(shù)實現(xiàn)注入
        /// </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 發(fā)送 form-data 形式的請求來上傳文件,可以按照以下步驟進行操作:

創(chuàng)建一個 HttpClient 實例:

HttpClient client = new HttpClient();

使用 MultipartFormDataContent 類創(chuàng)建一個 form-data 實例:

MultipartFormDataContent formData = new MultipartFormDataContent();

添加文件內(nèi)容到 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” 是表單字段名。

發(fā)送 POST 請求:

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

處理響應結(jié)果:

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
                {
                    // 處理錯誤情況
                }
            }
        }
    }

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論