flutter - 如何在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 标头中使用以前生成的不记名令牌。
解决方案
另一种选择是使用 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);
}
推荐阅读
- php - 我的 SQL/PHP 准备好的语句有问题
- python - 使用 Colab 和 pyngrok 进行 Streamlit - 无法完成隧道连接 - 版本问题?
- python-3.x - 使用 Selenium Python 在 Google 主页上单击 Google 搜索按钮时出现元素不可交互错误
- javascript - Firebase 按文档 ID PLUS 属性值查询
- python - rdd(pyspark)索引中的逗号分隔数据超出范围问题
- sql - PostgreSQL - 转换生成的列类型
- reactjs - 如何使用 Django Rest Framework 发布包含文件的嵌套数据?
- javascript - 如何获取每个匹配元素的特定子元素的数量
- javascript - 如何使用本地存储和 JavaScript 创建俄罗斯方块分数计数器
- python - 在 Python 中对嵌套字典进行排序