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 code above I get this error: An existing connection was forcibly closed by the remote host I went over the code a few times and everything looks fine, some articles suggest the error I'm getting is a server issue but when i try with R-client it works fine
This can be caused if the client and server can't agree on a version of the TLS protocol to use.
I think it's the case that .Net 4.5.2 and earlier default to v1, with v1.2 deactivated if it's included in the framework. (In .Net 4.6.*, v1.2 is the default.)
To enable v1.2 in 4.5.2 you can use:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
(I believe this enables it for the whole application domain?)
Solved the issue (against a different website) for me, anyway.
please change code according to below
1) problem is with https. you need to add proper certificate for it.
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 bypass cerificate error When developing or dealing with self signed certs you can ignore untrusted cert errors with the following: ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With