Most answers here suggest to use the typical pattern:
using (var httpClient = new HttpClient())
{
}
because of the IDisposable interface. Please don't!
Microsoft tells you why:
And here you can find a detailed analysis whats going on behind the scenes:
You're using HttpClient wrong and it is destabilizing your software
Official Microsoft link: HttpClient
HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.
Regarding your SSL question and based on Improper Instantiation antipattern # How to fix the problem
Here is your pattern:
class HttpInterface
{
private static readonly HttpClient client;
static HttpInterface()
{
var handler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = delegate { return true; },
};
var handler = new WebRequestHandler()
{
ServerCertificateValidationCallback = delegate { return true; },
ServerCertificateCustomValidationCallback = delegate { return true; },
};
client = new HttpClient(handler);
}
.....
var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");
using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
{
using (HttpContent respContent = resultMsg.Content)
{
return respContent.ReadAsStringAsync().Result;
}
}
}