Http client an existing connection was forcibly closed by the remote host
What am I doing wrong here?
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("mobile_numbers", "5555555555"),
new KeyValuePair<string, string>("message", "Whoo hahahahah")
});
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.iwin.co.za");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "134134134");
HttpResponseMessage response = client.PostAsync("iwin/api/v1/messages", formContent).Result;
When I run the code above, I get this error: The existing connection was forcibly closed by the remote host I went through the code several times and everything looked good, some articles point out the error I get is a server problem, but when I try to use R- client, it works fine
source to share
This can be caused if the client and server cannot agree on the version of the TLS protocol in use.
I think in this case .Net 4.5.2 and earlier defaults to v1, with v1.2 being deactivated if included in the framework. (In .Net 4.6. *, V1.2 by default.)
To enable v1.2 in 4.5.2 you can use:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
(I believe this allows it for the entire application domain?)
Solved the problem anyway (against another website).
source to share
please change the code according to below
1) the problem is with https. you need to add the correct certificate for this.
Dictionary<string, string> formContent= new Dictionary<string, string>();
mapObject.Add("mobile_numbers","5555555555");
mapObject.Add("message","Whoo hahahahah")
var jsonString = JsonConvert.SerializeObject(formContent);
WebRequestHandler handler = new WebRequestHandler();
X509Certificate2 certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("https://api.iwin.co.za");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer 134134134");
HttpResponseMessage response = client.PostAsync("/iwin/api/v1/messages", getHttpContent(jsonString)).Result;
another function to convert json to HttpContent
private static HttpContent getHttpContent(string jsonString)
{
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
return content;
}
or you can work around the Cerificate error When developing or working with self-signed certificates, you can ignore untrusted certificate errors with the following: ServicePointManager.ServerCertificateValidationCallback + = (sender, cert, chain, sslPolicyErrors) => true;
source to share