android - 不记名令牌请求http颤动
问题描述
我需要为我的 API 发送我的令牌。我将我的令牌保存在 SharedPreferences 中,我可以恢复它。我的 API 需要一个,带有 Bearer 但怎么做?
我用授权、Http 等进行了测试。
保存在 SP 中的方法
Future<bool> setToken(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString('token', value);
}
Future<String> getToken() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('token');
}
Future<Candidate> candidateAuth({Map map}) async {
String url = 'http://10.0.2.2:3000/v1/api/auth/candidate';
await http
.post(url,
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
body: jsonEncode(map))
.then((response) {
if (response.statusCode == 201) {
token = Candidate.fromJson(json.decode(response.body)).token;
Candidate().setToken(token);
return Candidate.fromJson(json.decode(response.body));
} else {
throw Exception('Failed auth');
}
});
}
}
我的 API 调用:
Future<List<Theme>> getThemes() async {
String url = 'http://10.0.2.2:3000/v1/api/theme';
String token;
Candidate().getToken().then((value) {
token = value;
});
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print(response);
if (response.statusCode == 200) {
List themesList = jsonDecode(response.body);
List<Theme> themes = [];
for (var themeMap in themesList) {
themes.add(Theme.fromJson(themeMap));
}
return themes;
} else {
throw Exception('Failed to load themes');
}
}
我的 API 返回错误 401:未经授权
解决方案
token
可能不会在它调用时设置http.get
。将其更改为
String token = await Candidate().getToken();
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print(response);
所以它肯定设置了正确的值。
推荐阅读
- hl7 - 是否需要 OBR 段才能查看 HL7 消息中的 OBX 段附件?
- java - 如何禁用默认的 Spring OAuth2 REST API?
- erlang - 使用 Erlang 列表理解查找元素
- android - onLayoutChange() 调用次数过多
- python-3.x - File.choose python 中的等价物?
- replace - Netezza,有没有办法用多个字符替换一个字符?
- python - 如何使用 boto 获取 dynamodb 表属性的空值
- menu - 在主菜单中显示前 2 个级别
- c# - appsettings-configuration 中的 Serilog PushProperty 不起作用
- javascript - 模糊内容时
模糊在内容上,但 blur 是在原始标题文本 ASP.NET JavaScript 下