我有从登录名获得的Api密钥。如何使用该密钥向服务器发出http.get请求?
这是我的钥匙:
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTU5MTc3NDg4LCJqdGkiOiIxZGU5MzlkNTNiYWQ0NDM4OWZjOGQ5MDJmYmRkMzYzMyIsInVzZXJfaWQiOjF9.vQFnfQSeTgxeOav--H4a5nf2Rs0xMWyDRewp9kkZXks"
运动课:
class Exercise {
final int id;
final String name;
Exercise(this.id, this.name);
Exercise.fromJson(Map<String, dynamic> j)
: id = j['id'],
name = j['name'];
}
获取不带令牌的请求(无法正常工作,我需要一个解决方案):
Future<List<Exercise>> _getExercises() async {
http.Response data = await http.get(
'url:8000/api/database/exercises/');
List jsonData = json.decode(data.body);
List<Exercise> allExercises = jsonData.map<Exercise>((j) => Exercise.fromJson(j)).toList();
return allExercises;
}
答案 0 :(得分:0)
您需要设置请求的标题
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization' : 'Bearer TOKENHERE'
};
await http.get(
'url:8000/api/database/exercises/',headers:userHeader)
但是我建议您尝试一下https://pub.dev/packages/dio 您只需将令牌提供给拦截器就很容易,然后它将为您添加令牌
var http = new Dio();
InterceptorsWrapper tokenInterceptor;
addTokenInterceptor(token) {
// Add interceptor
tokenInterceptor = InterceptorsWrapper(onRequest: (Options options) {
options.headers['Authorization'] = "Bearer " + token;
});
http.interceptors.add(tokenInterceptor);
}
removeTokenInterceptor() {
http.interceptors.remove(tokenInterceptor);
}
之后,只需使用http对象执行http服务
答案 1 :(得分:0)
我认为您正试图在请求中传递您的访问令牌。 您可以像这样在标头中传递令牌:
http.get(url, headers: <String,String>{'access':token});