API 在使用 RESTSHARP 时返回错误
API is returning error when using RESTSHARP
当使用 RestSharp 调用 API 时出现此错误:
The underlying connection was closed: An unexpected error occurred on
a send.
我已确认我的客户端 ID、机密、用户名和密码正确无误。我可以在 PowerShell 中毫无问题地执行此操作。
public string GetTokenForBrightIdea()
{
RestClient restclient = new RestClient(_uri);
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _clientSecret);
request.AddParameter("username", _clientUsername);
request.AddParameter("password", _clientPassword);
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
return JsonConvert.DeserializeObject<Dictionary<string, object>>(
responseJson)["access_token"].ToString();
}
使用 RestSharp 完成这项工作时,我错过了什么?
事实证明,因为这个调用是 HTTPS,所以我需要添加以下代码行
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
对于 .Net 3.5 和 4.0,您可以尝试在 RestSharp 客户端初始化之前放置这行代码:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
这对我来说效果很好:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
当使用 RestSharp 调用 API 时出现此错误:
The underlying connection was closed: An unexpected error occurred on a send.
我已确认我的客户端 ID、机密、用户名和密码正确无误。我可以在 PowerShell 中毫无问题地执行此操作。
public string GetTokenForBrightIdea()
{
RestClient restclient = new RestClient(_uri);
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _clientSecret);
request.AddParameter("username", _clientUsername);
request.AddParameter("password", _clientPassword);
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
return JsonConvert.DeserializeObject<Dictionary<string, object>>(
responseJson)["access_token"].ToString();
}
使用 RestSharp 完成这项工作时,我错过了什么?
事实证明,因为这个调用是 HTTPS,所以我需要添加以下代码行
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
对于 .Net 3.5 和 4.0,您可以尝试在 RestSharp 客户端初始化之前放置这行代码:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
这对我来说效果很好:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;