Http Post 在 Postman 中有效,但在 Flutter 中无效

Http Post is working in Postman, but not Flutter

编辑:我找到了解决方案并回答了问题。

我正在尝试在我的应用程序中 POST 到 Instagram API。 POST 在 Postman 中运行良好,但在我的 flutter 代码中,我总是收到错误响应: {error_type: OAuthException, code: 400, error_message: Invalid platform app} 。我一定是在颤抖中做错了什么 POST 但我不知道是什么。

这是我的 Postman POST(每次都有效)以及正确的 body 回复:

这是我的 Dart/Flutter 代码,它给我错误:

        var clientID = '708XXXXXXXX';
        var clientSecret = '37520XXXXXXXXXXXXX';
        var grantType = 'authorization_code';
        var rediUrl = 'https://httpstat.us/200';
        
        var urlTwo = 'https://api.instagram.com/oauth/access_token';
        var body = json.encode({
          'client_id': clientID,
          'client_secret': clientSecret,
          'grant_type': grantType,
          'redirect_uri': rediUrl,
          'code': _accessCode
        });
                
        print('Body: $body');

        var response = await http.post(urlTwo,
          headers: {
            'Accept': '*/*',
            'Content-Type': 'application/json',
          },
          body: body,
        );

        print(json.decode(response.body));

我在另一个线程上读到了错误,他们说 post 为 x-www-formurlencoded.. 当我将 Content-Type 切换到这个时,我得到了同样的错误。

我在Flutter中得到的错误:

{error_type: OAuthException, code: 400, error_message: Invalid platform app}

我检查了三次,我在 Postman 和 Flutter 中使用了所有相同的值。我已经尝试将值作为字符串和数字。

当我打印 body:

Body: {"client_id":"70000edited","client_secret":"37520634edited","grant_type":"authorization_code","redirect_uri":"https://httpstat.us/200","code":"AQCs-H3cIU0aF1o2KkltLuTmVMmJ-WJnZIhb9ryMqYedited"}

试一次

final response = await http.post(urlTwo,
   body: body,
   headers: {
     "Accept": "application/json",
     "Content-Type": "application/x-www-form-urlencoded"
   },
   encoding: Encoding.getByName("utf-8"));

我终于用 Map 让它工作了。这很奇怪,因为其他尝试我也使用了地图(我一直在尝试许多堆栈溢出答案)。无论如何,这是我使用的工作代码:

        var urlTwo = 'https://api.instagram.com/oauth/access_token';
        var clientID = '7080000';
        var clientSecret = '375XXXXXX';
        var grantType = 'authorization_code';
        var rediUrl = 'https://httpstat.us/200';

        var map = new Map<String, dynamic>();
        map['client_id'] = clientID;
        map['client_secret'] = clientSecret;
        map['grant_type'] = grantType;
        map['redirect_uri'] = rediUrl;
        map['code'] = _accessCode;

        http.Response response = await http.post(
          urlTwo,
          body: map,
        );

        var respData = json.decode(response.body);
        print(respData);