You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.1 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace HttpClientStudy.Core
{
/// <summary>
/// 管道方式 HttpClient客户端
/// </summary>
public class PipelineHttpClient
{
public List<DelegatingHandler> HttpMessageHandlers { get; set; }
public PipelineHttpClient()
{
HttpMessageHandlers = new List<DelegatingHandler>()
{
new CustomHeadersHandler(),
new LoggingHandler(),
};
}
public PipelineHttpClient(List<DelegatingHandler> httpMessageHandlers)
{
HttpMessageHandlers = httpMessageHandlers;
if (httpMessageHandlers == null || httpMessageHandlers?.Count == 0)
{
HttpMessageHandlers = new List<DelegatingHandler>();
}
}
public void AddDelegatingHandler(DelegatingHandler handler)
{
HttpMessageHandlers.Add(handler);
}
public HttpClient CreateHttpClient()
{
//创建处理器链
//最终处理器最后一个请求处理程序默认是SocketsHttpHandler.
HttpMessageHandler currentPipeLine = new SocketsHttpHandler()
{
//自定义配置
PooledConnectionLifetime = TimeSpan.FromSeconds(120),
};
//pipeline = new CustomHeadersHandler() { InnerHandler = pipeline};
//pipeline = new LoggingHandler () { InnerHandler = pipeline};
//倒序组装:完成后执行顺序与注册顺序一致
HttpMessageHandlers.Reverse();
for (int i = 0; i < HttpMessageHandlers.Count; i++)
{
HttpMessageHandlers[i].InnerHandler = currentPipeLine;
currentPipeLine = HttpMessageHandlers[i];
}
// 利用管道创建HttpClient
var httpClient = new HttpClient(currentPipeLine);
return httpClient;
}
}
}