Home > Software design >  Flutter http request not accepting headers but it works on postman
Flutter http request not accepting headers but it works on postman

Time:04-29

I am getting a really frustrating experience. Am making a post request to an api, works well on postman but refuses to work on flutter.

Postman Image

Here is the error response which tells me this is an issue with the headers.

 {"message":"Missing/Incorrect Security Key Header","apiVersion":"v1","transactionRef":"N202204281825312267","data":null,"error":{"code":401,"message":"Authorization failed for this request!"}}

My Request

 static Future<dynamic> postRequest(String url) async {
    http.Response response = await http.post(Uri.parse(url),
      headers: <String, String>{
        "Access-Key" : "6a637874-0394-4d9d-a803-86323c1ddc4d",
        "Accept": "application/json",
        "Content-Type" : 'application/json',
      },
    );
    print(response.body);
    print(url);
    try {
      if (response.statusCode == 200) {
        String data = response.body;
        var decodedData = jsonDecode(data);
        return decodedData;
      } else {
        return response.body;
      }
    } catch (e) {
      return response.body;
    }
  }

CodePudding user response:

I would like to introduce you to another package in Flutter which makes working with http requests much easier, it's called Dio. Everything works the same, it also removes some boilerplate by default, you don't have to parse url, you can directly pass the url string. You don't have to encode/decode json. Instead of passing headers attribute in http, dio works the following way,

Add the dependency to pubspec.yaml file and import dio.dart file.

Instructions can be found here https://pub.dev/packages/dio

Here's an example:

Future fetchData () async {
  Dio dio = new Dio();
  final response = await dio.post(
  url,
  options: Options(
    headers: {'Access-Key': 'key'},
  );
  print(response.data);
}
  • Related