首页 > 解决方案 > 如何在flutter中获取注册api的令牌

问题描述

我有用于生成令牌的 URL,通过使用 http post 我正在获取令牌。现在我的问题是我必须使用生成的令牌作为注册 api(另一个 api)中的标头。

Future<Map<String, dynamic>> fetchPost() async {
  print('feg');
  final response = await http.post(
    '/rest_api/gettoken&grant_type=client_credentials',
    headers: {HttpHeaders.authorizationHeader: "Basic token"},
  );
  final responseJson = json.decode(response.body);
  print("Result: ${response.body}");
  //return Post.fromJson(responseJson);
  return responseJson;
}

在这里,我得到了我想使用该令牌来注册 api 的令牌

  Future<Register> fetchPost() async {
  print('feg');
  final response = await http.post(
    'your base url/rest/register/register',
    headers: { HttpHeaders.authorizationHeader: "Bearer token",
      HttpHeaders.contentTypeHeader: "application/json"},
  );
  var   responseJson = json.decode(response.body);
  print("Result: ${response.body}");
  return Register.fromJson(responseJson);
}

这是注册 api 的 post 方法,我想在上面的 api 标头中使用以前生成的不记名令牌。

标签: flutterdarthttp-headers

解决方案


另一种选择是使用 Keychain (Android) 和 Keystore (iOS) https://pub.dev/packages/flutter_secure_storage的安全存储

添加你的 pubspec.yaml

    dependencies:
  flutter_secure_storage: ^3.2.1+1

在您的代码中,导入库并保存

Future<Map<String, dynamic>> fetchPost() async {
final storage = FlutterSecureStorage();
  print('feg');
  final response = await http.post(
    '/rest_api/gettoken&grant_type=client_credentials',
    headers: {HttpHeaders.authorizationHeader: "Basic token"},
  );
  final responseJson = json.decode(response.body);
  print("Result: ${response.body}");
  //return Post.fromJson(responseJson);

  /// Write token in token key with security
  await prefs.write(key: 'token',value: responseJson['token']);
  return responseJson;
}

如果您需要阅读,请使用以下代码:

Future<Register> fetchPost() async {
final storage = FlutterSecureStorage();
  print('feg');
  String token = await storage.read(key: 'token');
  final response = await http.post(
    'your base url/rest/register/register',
    headers: { HttpHeaders.authorizationHeader: token,
      HttpHeaders.contentTypeHeader: "application/json"},
  );
  var   responseJson = json.decode(response.body);
  print("Result: ${response.body}");
  return Register.fromJson(responseJson);
}

推荐阅读