承载令牌请求HTTP抖动

时间:2019-09-24 11:19:13

标签: android mobile flutter flutter-layout

我需要发送我的API令牌。 我将令牌保存在SharedPreferences中,可以恢复它。 我的API需要一个,与Bearer一起使用,但怎么办?

我用Authorization,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:未经授权

6 个答案:

答案 0 :(得分:1)

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);

因此可以确定它设置了正确的值。

答案 1 :(得分:1)

问题是您以不同的方式分配令牌。

执行此操作时,await asyncFunction(); Dart将等到完成为止。但是,当您这样做asyncFunction().then((value) => print)时,这将告诉Dart它可以继续执行您的代码,并且当asyncFunction完成时,不打印值。

您的情况就是这样

Candidate().getToken().then((value) {
      token = value;
    });

这里是一个示例,在Dart Pad上执行。

Future.dart

答案 2 :(得分:1)

您也可以使用此方法

String token = await Candidate().getToken();
final response = http.get(url,
        headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});

答案 3 :(得分:0)

您只需要在请求标头中添加授权字段:

getProfile() async {
print(getToken());
var token = await getToken();
http.post(
      "$url",
      headers: {
        "Content-Type": "application/json",
        'Authorization': 'Bearer $token',
      },
      encoding: Encoding.getByName("utf-8"),
    ).then((response) {
      print(datafromurl);
      if (response.statusCode == 200) {
         print(json.decode(response.body));
      }
    });
}

答案 4 :(得分:0)

这是发布请求的示例。您只需要添加标题“ Authorization”:“ Bearer $ token”

final response = await http.post(
  url,
  headers: {'Authorization': 'Bearer $token'},
);

答案 5 :(得分:-1)

final response = await http.get(url);
if (response.statusCode == 200) {
  final body = jsonDecode(response.body);
  //print(body);
  final Iterable json = body;
  return json.map((country) {
    return Country.fromJson(
        country); // if you use "{}", you must use return
  }).toList();