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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C#將布爾類型轉(zhuǎn)換成字節(jié)數(shù)組的方法
這篇文章主要介紹了C#將布爾類型轉(zhuǎn)換成字節(jié)數(shù)組的方法,涉及C#中字符串函數(shù)的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04C# 9 中新加入的關鍵詞 init,record,with
這篇文章主要介紹了C# 9 中新加入的關鍵詞 init,record,with的相關資料,幫助大家更好的理解和學習c# 9,感興趣的朋友可以了解下2020-08-08C#實現(xiàn)Excel數(shù)據(jù)導入到SQL server數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了在C#中如何實現(xiàn)Excel數(shù)據(jù)導入到SQL server數(shù)據(jù)庫中,文中的示例代碼簡潔易懂,希望對大家有一定的幫助2024-03-03