如何在 flutter Dio post 请求中设置授权 header 中的令牌

How to set token in authorization header in flutter Dio post request

我想使用 Dio 在我的 post 请求的授权 header 中设置一个令牌。我尝试使用两个选项设置 header。而且两者都不起作用。第一种方式抛出错误,第二种方式,没有数据发送到服务器。使用 Dio()

从共享首选项添加授权令牌并在 post 请求中将其作为 header 发送的最佳方式是什么

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

String token = "";

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

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

我使用第一种方式发送数据 header:

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

这会引发错误

Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [302]

我使用的第二种方法是将令牌添加到 headers:

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

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

这样试试

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