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();
下载图片1
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);
下载文件2
static async Task Main(string[] args)
{
string url = "https://example.com/yourfile.dat"; // 替换为实际的文件下载地址
string fileName = "downloaded_file.dat"; // 下载后保存的文件名
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
using (Stream contentStream = await response.Content.ReadAsStreamAsync())
{
// 保存文件
using (FileStream fileStream = File.Create(fileName))
{
await contentStream.CopyToAsync(fileStream);
}
}
Console.WriteLine("文件下载成功!");
}
else
{
Console.WriteLine($"下载文件失败,状态码: {response.StatusCode}");
}
}
}
}
url 文件,上传到其他url地址
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string downloadUrl = "https://example.com/yourfile.dat"; // 下载文件的URL
string uploadUrl = "https://example.com/upload"; // 上传文件的URL
// 下载文件
byte[] fileBytes;
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(downloadUrl))
{
if (response.IsSuccessStatusCode)
{
fileBytes = await response.Content.ReadAsByteArrayAsync();
}
else
{
Console.WriteLine($"下载文件失败,状态码: {response.StatusCode}");
return;
}
}
}
// 上传文件 //可以参考 post form-data上传文件(下一个例子)
using (HttpClient client = new HttpClient())
{
ByteArrayContent content = new ByteArrayContent(fileBytes);
using (HttpResponseMessage response = await client.PostAsync(uploadUrl, content))
{
if (response.IsSuccessStatusCode)
{
Console.WriteLine("文件上传成功!");
}
else
{
Console.WriteLine($"上传文件失败,状态码: {response.StatusCode}");
}
}
}
}
}
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
{
// 处理错误情况
}
}
}
}