繁体   English   中英

使用HttpClient和HttpWebRequest来获取Https TLS1.2

[英]Using HttpClient & HttpWebRequest for Https TLS1.2

在控制台应用程序中,尝试点击配置了TLS 1.2的“https”端点。

在C#中使用HttpClient时,我从端点获得成功响应

       HttpClient httpClient = new HttpClient();

        //specify to use TLS 1.2 as default connection
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

        httpClient.BaseAddress = new Uri("HTTPSENDPOINT");
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var content = new StringContent("POSTDATA");
        var task = httpClient.PostAsync("/Token", content);

        task.Wait();

        Console.WriteLine(task.Result.Content.ReadAsStringAsync().Result.ToString());

但是在使用HttpWebRequest时

       var request = (HttpWebRequest)WebRequest.Create("HTTPSENDPOINT/Token");
       var postData = "POSTDATA";
        var data = Encoding.ASCII.GetBytes(postData);

        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream()) // Getting Error in GetRequestStream() method call
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

我收到了以下错误

The request was aborted: Could not create SSL/TLS secure channel.

使用HttpWebRequest时,请指导我做错了什么?

您需要调用WebRequest.Create方法之前设置SecurityProtocol属性。

更新:

让我添加一些细节来解释为什么这应该是正确的。

看一下来自referencesource.microsoft.comWebRequest.Create(string)方法的源代码。

返回值为:

return Create(new Uri(requestUriString), false);

现在,让我们看看Create(Uri, bool)方法,它从WebRequestPrefixElement.Creator.Create(Uri)返回一些对象。

CreatorWebRequestPrefixElement一个属性,它的类型为IWebRequestCreate 在您的情况下, IWebRequestCreate将是一个HttpRequestCreator对象。

查看HttpRequestCreator.Create方法的代码:

public WebRequest Create( Uri Uri ) {
    //
    // Note, DNS permissions check will not happen on WebRequest
    //
    return new HttpWebRequest(Uri, null);
}

最后,让我们看看那个HttpWebRequest构造函数。 你会在那里看到一个很长的代码,但真正重要的是这一行:

SslProtocols = (SslProtocols)ServicePointManager.SecurityProtocol;

因此, SecurityProtocol值将分配给名为SslProtocols的属性。 因此,现在很明显使用SecurityProtocol并在调用Create方法时将其保存到HttpWebRequest对象,因此调用Create 之后更改SecurityProtocol不会更改HttpWebRequest对象使用的协议。

您的问题似乎非常接近此问题请求已中止:无法创建SSL / TLS安全通道

我注意到他们没有将SecurityProtocolType.Ssl3添加到您已添加的其他内容中。 尝试将enum协议实现为最受好评的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM