May*_*iXx 19 mobile android flutter flutter-layout
我需要为我的 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');
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我的 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');
}
}
Run Code Online (Sandbox Code Playgroud)
我的 API 返回错误 401:未经授权
Che*_*ddy 40
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);
Run Code Online (Sandbox Code Playgroud)
这样它肯定会设置为正确的值。
小智 9
你也可以使用这个方法
String token = await Candidate().getToken();
final response = http.get(url,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});
Run Code Online (Sandbox Code Playgroud)
只需要在请求头中添加授权字段即可:
var token = await getToken();
http.post(
"$url",
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer $token',
},
encoding: Encoding.getByName("utf-8"),
).then((response) {
if (response.statusCode == 200) {
print(json.decode(response.body));
// Do the rest of job here
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36889 次 |
| 最近记录: |