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

1,578

try like this

 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
});
Share:
1,578
blackbird
Author by

blackbird

Updated on December 25, 2022

Comments

  • blackbird
    blackbird over 1 year

    I want to set a token in the authorization header on my post request using Dio. I have tried to set the header using two options. And both don't work. The first way throws an error, the second, no data is sent to the server. What is the best way of adding an authorization token from shared preference and sending it as a header on a post request using Dio()

    I am saving the token on SharedPreference when a user signs in and accesses it:

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

    The first way am using to send the data with the 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
        });
    

    which throws an error

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

    The second way am using to add the token to the 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; }));
      }
    

    this way I don't get an error, but no data is sent to the server.

  • GJJ2019
    GJJ2019 over 3 years
    Im assuming token is valid and not null in that method
  • blackbird
    blackbird over 3 years
    yes the token is always valid, I also found another issue, my backend produces cookies with a unique jsessionID, that is required also on the headers. That's where am stuck currently, hard coding the cookie works but it expires after a while so the reqeust cant be send.