服务器团队说这个 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 的问题。