gpt4 book ai didi

c# - HttpClientHandler/请求被中止 : Could not create SSL/TLS secure channel

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:17 26 4
gpt4 key购买 nike

服务器团队表示此 HTTPS 网站一切正常,但是使用 HTTPClient 时以下代码返回“请求已中止:无法创建 SSL/TLS 安全通道。”错误和同时通过返回预期数据完美地工作。

public async Task<string> GetDataAsync(string baseAddress, string relativeAddress, string token)
{
string responseBodyAsText = string.Empty;
string responseStatusCode = string.Empty;
try
{
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential(token, token);
using (HttpClient client = new HttpClient(handler))
{
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, relativeAddress))
{
using (HttpResponseMessage response = await client.SendAsync(request))
{
responseBodyAsText = await response.Content.ReadAsStringAsync();
responseStatusCode = ReturnStatusCode(response);
}
}
}
}
}
catch (Exception e)
{
responseBodyAsText = BuildErrorMessage("response", "error", e.InnerException.Message, responseStatusCode);
}
return responseBodyAsText;
}

为了以不同的方式解决这个问题,我编写了另一个使用 HTTPWebRequest 和 HTTPWebResponse 的方法。这段代码直到现在才给我这个错误“请求被中止:无法创建 SSL/TLS 安全通道。”;但是我想将其发布以找出可能的问题是什么?

    public async Task<string> GetDataAsync(string url, string token)
{
string responseString = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Trim());
request.Method = "GET";
request.ContentType = "application/xml";
request.Headers[HttpRequestHeader.Authorization] = GetAuthorizationText(token.Trim());

var response = (HttpWebResponse)await request.GetResponseAsync();
if (response != null)
{
var responseStream = new StreamReader(response.GetResponseStream());
responseString = await responseStream.ReadToEndAsync();
if (responseString.Trim().Length == 0)
throw new InvalidDataException("No Content");
}
else
throw new NullReferenceException("Reponse is null");
}
catch (WebException we)
{
responseString = BuildErrorMessage("response", "error", we.Response.Headers["Status"].ToString());
}
catch (Exception ex)
{
WriteDiagnosticsInformation(ex);
responseString = BuildErrorMessage("response", "error", ex.Message);
}

return responseString;
}

请分享您的想法,但我怀疑这可能是使用 HTTPClient 的问题。

最佳答案

试着放这个

ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

在一切之前

关于c# - HttpClientHandler/请求被中止 : Could not create SSL/TLS secure channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19591318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com