本文介绍了使用 RESTSHARP 时 API 返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 RestSharp 调用 API 时出现此错误:

When use RestSharp to call an API I get this error:

底层连接已关闭:发生意外错误发送.

我已确认我的客户 ID、密码、用户名和密码正确无误.我可以在 PowerShell 中毫无问题地做到这一点.

I've verified that my client ID, secret, username, and password are correct. I'm able to do this without issues in 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 进行这项工作时,我缺少什么?

What am I missing when using RestSharp to make this work?

推荐答案

原来因为这个调用是 HTTPS 我需要添加以下代码行

So it turns out that because this call was HTTPS i needed to add the following line of code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

这篇关于使用 RESTSHARP 时 API 返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 05:32