我想像在本article中那样使用HttpClient
时减少连接数量,而不用在HttpClient
语句中包装using
的创建。但是我需要针对不同的请求使用不同的证书。
我在基类中将HttpsClient
设为静态,并在静态构造函数中创建了该实例以及静态WebRequestHandler
的实例。为方法SetHandler
添加了证书并设置了处理程序的其他属性。然后在ExecuteRequestAsync
中调用SetHandler
,我希望它可以将属性填充到HttpClient
处理程序的静态实例中。
private static readonly WebRequestHandler _handler;
private static readonly HttpClient _httpClient;
private readonly string _uri;
private readonly IDictionary<string, string> _headers;
private readonly string _customContentType;
private readonly int _timeout;
private readonly X509Certificate _clientCertificate;
private readonly X509Certificate _trustedServerCertificate;
private readonly bool _allowAutoRedirect;
private readonly bool _allowErrorStatusCodes;
private readonly CookieContainer _cookie;
private readonly IProtocolLogger _logger;
static ProtocolHttpService()
{
_handler = new WebRequestHandler();
_httpClient = new HttpClient(_handler);
}
public ProtocolHttpService(
string uri,
IDictionary<string, string> headers = null,
string customContentType = null,
int timeout = MAX_TIMEOUT,
X509Certificate clientCertificate = null,
X509Certificate trustedServerCertificate = null,
bool allowAutoRedirect = false,
bool allowErrorStatusCodes = false,
CookieContainer cookie = null,
IProtocolLogger logger = null)
{
_uri = uri;
_headers = headers;
_customContentType = customContentType;
_timeout = timeout;
_clientCertificate = clientCertificate;
_trustedServerCertificate = trustedServerCertificate;
_allowAutoRedirect = allowAutoRedirect;
_allowErrorStatusCodes = allowErrorStatusCodes;
_cookie = cookie;
_logger = logger;
}
static ProtocolHttpService()
{
_handler = new WebRequestHandler();
_httpClient = new HttpClient(_handler);
}
private async Task<CommunicationStats> ExecuteRequestAsync(HttpMethod method, string requestText)
{
var sw = Stopwatch.StartNew();
using (var cancellationTokenSource = new CancellationTokenSource(_timeout))
{
var cancellationToken = cancellationTokenSource.Token;
var request = new HttpRequestMessage
{
Method = method,
RequestUri = new Uri(_uri)
};
if (!string.IsNullOrEmpty(requestText))
{
request.Content = new StringContent(requestText, Encoding.UTF8, _customContentType);
}
AddHeaders(request);
SetHandler();
var response = await _httpClient.SendAsync(request, cancellationToken);
var responseText = await response.Content.ReadAsStringAsync();
return CommunicationStats.Create(response.StatusCode, _uri, requestText, responseText, sw.Elapsed);
}
private void SetHandler()
{
if (_cookie != null)
{
_handler.CookieContainer = _cookie;
}
if (_clientCertificate != null &&
!_handler.ClientCertificates.Contains(_clientCertificate))
{
_handler.ClientCertificates.Add(_clientCertificate);
}
_handler.AllowAutoRedirect = _allowAutoRedirect;
}
在调试过程中,我发现HttpClient
的处理程序属性未设置为应在SetHandler
中设置。