Flutter API 请求 BadState 响应

问题描述 投票:0回答:2

我目前正在尝试用flutter实现API请求。我已经在Postman中实现了ressuest并尝试了所有数据。结果成功了。然后我尝试在我的程序中实现这个请求。但是,我这里有一个问题,这就是为什么我总是得到 ResponseCode 400。但是,我无法再解释原因。我在这里使用FatSecret API

根据文档,我用于此请求的代码需要授权标头。它由 clientID 和 clientSecret 组成。正文还包含“grant_type”:“client_credentials”和“scope”:“premier”。

class FatSecretAPI extends ConsumerWidget {
  const FatSecretAPI({super.key});

final String clientId = "...";
final String clientSecret = "...";

  Future<FatSecretToken> fetchAccesToken() async {
    final response = await http
        .post(Uri.parse("https://oauth.fatsecret.com/connect/token"),
        body: {
      "grant_type": "client_credentials",
      "scope": "premier"
    }, headers: {
           HttpHeaders.authorizationHeader: "Basic ${base64.encode(utf8.encode('$clientId:$clientSecret'))};"
    });
    if (response.statusCode == 200) {
      var object = FatSecretToken.fromJson(
          jsonDecode(response.body) as Map<String, dynamic>);
      print(object.accessToken);
      return object;
    } else {
      print(response.statusCode);
      throw Exception("Failed to load token");
    }
  }

  Future<void> loadToken(WidgetRef ref) async {
    final token = await fetchAccesToken();
    ref.read(accesTokenProvider.notifier).state = token.accessToken;
  }
}

class FatSecretToken {
  final String accessToken;
  final String tokenType;
  final int expiresIn;

  FatSecretToken(
      {required this.accessToken,
      required this.tokenType,
      required this.expiresIn});

  factory FatSecretToken.fromJson(Map<String, dynamic> json) {
    return FatSecretToken(
      accessToken: json['access_token'],
      tokenType: json['token_type'],
      expiresIn: json['expires_in'],
    );
  }
}

这里实际上应该出现Json格式的响应,其中包含有关accesToken和token类型的信息。

flutter dart dart-html
2个回答
0
投票

我已经复制了整个事情,这就是它的工作原理。可能是因为;在 auth 标头中。这样它也更具可读性,并且可以轻松定制用于其他目的。您还应该外包秘密,以便它们更安全。

Future<FatSecretToken> getToken() async {
    final String basicAuth =
        'Basic ' + base64Encode(utf8.encode('$clientId:$clientSecret'));

    final Map<String, String> headers = {
      'Authorization': basicAuth,
      // 'Content-Type': 'application/x-www-form-urlencoded',
    };

    final Map<String, String> body = {
      'grant_type': 'client_credentials',
      'scope': 'premier barcode',
    };

    final response = await http.post(
      Uri.parse('https://oauth.fatsecret.com/connect/token'),
      headers: headers,
      body: body,
    );

    if (response.statusCode == 200) {
      var object = FatSecretToken.fromJson(
          jsonDecode(response.body) as Map<String, dynamic>);
      return object;
    } else {
      throw Exception('Failed to get token: ${response.reasonPhrase}');
    }
  }

0
投票

您代码中的问题是“;”看起来像。

您应该按如下方式更新“标题”部分:

 headers: {
    HttpHeaders.authorizationHeader:
        "Basic ${base64.encode(utf8.encode('$clientId:$clientSecret'))}"
  },

此外,“范围”值必须是“基本”

© www.soinside.com 2019 - 2024. All rights reserved.