我目前正在try 使用Ffltter实现一个API请求.我已经在Postman中实现了Resuest,并try 了所有数据.结果是成功的.然后我试图在我的计划中实现这个要求.然而,我这里有一个问题,这就是为什么我总是得到ResponseCode400.然而,我再也无法解释为什么.我在用这里的FatSecret API元.
根据文档,我用于此请求的代码需要授权头.它由客户ID和客户秘密组成.正文中还包含"GRANT_TYPE":"CLIENT_CREDICATIONS"和"SCOPE":"PRIMILER".
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和令牌类型的信息.