【问题标题】:How to set token in authorization header in fluttter Dio post request如何在颤振 Dio 发布请求的授权标头中设置令牌
【发布时间】:2021-03-03 16:19:40
【问题描述】:

我想使用 Dio 在我的发布请求的授权标头中设置一个令牌。我尝试使用两个选项设置标题。两者都不起作用。第一种方式抛出错误,第二种方式,没有数据发送到服务器。从共享首选项添加授权令牌并使用 Dio() 在发布请求中将其作为标头发送的最佳方法是什么

当用户登录并访问它时,我将令牌保存在 SharedPreference 上,如下所示

String token = "";

  @override
  void initState() {
    getToken();
  }

  void getToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString("token");
    setState((){});
  }

第一种发送数据的方式

 Future<FormsModel> createEntry(
      String id,
      String formName,
      String dataContent,
      String dateCreated,
      String dateUpdated,
      String userLocation,
      String imeI,
      String updatedBy) async {
    String apiUrl = "http://10.0.2.2:8080/api/v1/entry";
    Dio().options.headers["Authorization"] = "Bearer $token";
    await Dio().post(apiUrl, data: {
      "id": id,
      "formName": formName,
      "dataContent": dataContent,
      "dateCreated": dateCreated,
      "dateUpdated": dateUpdated,
      "userLocation": userLocation,
      "imeI": imeI,
      "updatedBy": updatedBy
    });

引发错误

未处理的异常:DioError [DioErrorType.RESPONSE]:Http 状态 错误 [302]

第二种将令牌添加到标头的方式

Future<FormsModel> createEntry(
      String id,
      String formName,
      String dataContent,
      String dateCreated,
      String dateUpdated,
      String userLocation,
      String imeI,
      String updatedBy) async {
    String apiUrl = "http://10.0.2.2:8080/api/v1/entry";
    await Dio().post(apiUrl, data: {
      "id": id,
      "formName": formName,
      "dataContent": dataContent,
      "dateCreated": dateCreated,
      "dateUpdated": dateUpdated,
      "userLocation": userLocation,
      "imeI": imeI,
      "updatedBy": updatedBy
    },
    options: Options( headers: {"authorization": "Bearer $token"},
    followRedirects: false,
    validateStatus: (status) { return status < 500; }));
  }

这样我不会出错,但没有数据发送到服务器。

【问题讨论】:

标签: flutter dart authorization access-token


【解决方案1】:

这样试试

 String apiUrl = "http://10.0.2.2:8080/api/v1";

 final dio = Dio(
    BaseOptions(
       connectTimeout: 30000,
       baseUrl: apiUrl',
       responseType: ResponseType.json,
       contentType: ContentType.json.toString(),
  ));

 dio.options.headers["Authorization"] = "Bearer $token";
 await dio.post("/entry" , data: {
  "id": id,
  "formName": formName,
  "dataContent": dataContent,
  "dateCreated": dateCreated,
  "dateUpdated": dateUpdated,
  "userLocation": userLocation,
  "imeI": imeI,
  "updatedBy": updatedBy
});

【讨论】:

  • 我假设令牌在该方法中有效且不为空
  • 是的,令牌始终有效,我还发现了另一个问题,我的后端生成具有唯一 jsessionID 的 cookie,这在标头上也是必需的。这就是目前卡住的地方,对 cookie 进行硬编码可以工作,但它会在一段时间后过期,因此无法发送请求。
猜你喜欢
  • 2013-07-07
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
相关资源
最近更新 更多