首页 > 解决方案 > 不记名令牌请求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:未经授权

标签: androidmobileflutterflutter-layout

解决方案


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

所以它肯定设置了正确的值。


推荐阅读