【问题标题】:http request in dart is not behaving the same as in postmandart 中的 http 请求的行为与 postman 中的不同
【发布时间】:2022-01-08 14:26:32
【问题描述】:

我正在尝试为在线投资经纪人 Questrade 编写一个使用公共 API 的程序。

您在网站上手动生成刷新令牌,然后将其传递给请求以获取访问令牌。

Use the token you copied to redeem it for an access token and the server or practice server URL using the following command:

https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token=

or

https://practicelogin.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token= 

我在 postman 中构造了如下的 GET 请求,它成功并接收到一个有效的 json 正文。

https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token=MT1men5gBhSXyv15e6j7gC4CrD8msq3P0

在 dart 中,我按如下方式构造请求...

static Future<AccessToken> getAccessToken(String refreshToken) async {
      var uri = Uri.https("login.questrade.com", "/oauth2/token?grant_type=refresh_token&refresh_token=$refreshToken");
      var response = await http.get(uri);
      print(response);
      var json = jsonDecode(response.body);
      return AccessToken.fromJson(json);
    }

但它给我的只是一个实际的 html 响应,看起来像是一个登录页面(太大而无法发布)。

所以看起来端点对这些请求的处理方式不同,但我无法弄清楚这两个请求有什么不同......

【问题讨论】:

    标签: http dart postman


    【解决方案1】:

    您正在创建错误的Uri,因为您使用路径作为编码数据的一种方式,但由于它会尝试编码&amp;,所以它不起作用。如果您打印您的 uri 对象,您可以看到问题:

    https://login.questrade.com/oauth2/token%3Fgrant_type=refresh_token&refresh_token=MT1men5gBhSXyv15e6j7gC4CrD8msq3P0
    

    相反,请执行以下操作,将数据提供给 Uri.https 构造函数:

    void main() {
      var refreshToken = 'MT1men5gBhSXyv15e6j7gC4CrD8msq3P0';
      var uri = Uri.https(
        'login.questrade.com',
        '/oauth2/token',
        <String, String>{
          'grant_type': 'refresh_token',
          'refresh_token': refreshToken,
        },
      );
      print(uri);
      // https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token=MT1men5gBhSXyv15e6j7gC4CrD8msq3P0
    }
    
    

    【讨论】:

    • 这只是给了我“糟糕的要求”。邮递员仍然可靠地成功。
    • @Scorb 您没有提供有关如何通过 Postman 调用 API 的详细信息(例如,如果您设置了任何标头)。但首先要检查 Dart 中生成的 URI 是否与 Postman 中生成的相同。如果你完全迷路了,请上传一些 Postman 配置的屏幕截图,以便我们验证你的 Dart 代码是否与 Postman 一样。
    • 我只是没有正确实施这个解决方案。我的坏:\
    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2021-01-05
    • 2019-11-23
    • 2022-01-02
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多