【问题标题】:Bearer token request http flutter不记名令牌请求http颤动
【发布时间】:2020-01-24 12:12:56
【问题描述】:

我需要为我的 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:未授权

【问题讨论】:

  • 未授权意味着您的令牌已过期,您需要获取新令牌
  • 不,当我在我的招摇中输入我的令牌时很好@VivekMishra

标签: android mobile flutter flutter-layout


【解决方案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);

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

【讨论】:

  • 每当我使用这种方法时,我最终都会得到一个空白版本的 Candidate,而不是获得原始的所需状态。任何人都可以根据这些小信息知道我缺少什么?
【解决方案2】:

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

当你这样做时await asyncFunction(); Dart 会等到它完成。但是,当你这样做 asyncFunction().then((value) =&gt; print) 时,它会告诉 Dart 它可以继续执行你的代码,并且当 asyncFunction 完成时会打印该值。

这就是你的情况发生的情况

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

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

Future.dart

【讨论】:

    【解决方案3】:

    你也可以用这个方法

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:
          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();
          

          【讨论】:

          • 添加一些描述来解释你的代码。
          【解决方案7】:

          这是该问题的另一种可能的解决方案。您必须等待 getToken() 函数的响应才能继续。您可以通过两种不同的方式完成它。使用“then”或“await”。

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

          【讨论】:

            猜你喜欢
            • 2022-01-07
            • 1970-01-01
            • 1970-01-01
            • 2020-12-11
            • 2022-08-04
            • 1970-01-01
            • 2021-08-02
            • 2017-03-20
            • 2021-05-18
            相关资源
            最近更新 更多