Http客户端远程主机强制关闭现有连接

时间:2017-05-29 11:15:54

标签: c# httpclient dotnet-httpclient

我在这里做错了什么?

        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;

当我运行上面的代码时,我收到此错误: 现有连接被远程主机强行关闭 我查了几次代码,一切看起来都很好,有些文章暗示我得到的错误是服务器问题,但是当我尝试使用R-client时工作正常

Http request

2 个答案:

答案 0 :(得分:12)

如果客户端和服务器无法就要使用的TLS协议版本达成一致,则可能会导致这种情况。

我认为.Net 4.5.2及更早版本默认为v1,如果v1.2包含在框架中,则停用v1.2。 (在.Net 4.6。*中,v1.2是默认值。)

要在4.5.2中启用v1.2,您可以使用:

System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

(我相信这可以在整个应用领域实现它吗?)

无论如何,为我解决了问题(针对不同的网站)。

答案 1 :(得分:1)

请根据以下

更改代码

1)问题在于https。你需要为它添加适当的证书。

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;

将json转换为HttpContent的另一个函数

  private static HttpContent getHttpContent(string jsonString)
        {
            var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            return content;
        }

或者您可以绕过证书错误 在开发或处理自签名证书时,您可以使用以下内容忽略不受信任的证书错误:ServicePointManager.ServerCertificateValidationCallback + =(sender,cert,chain,sslPolicyErrors)=&gt;真;