How to send custom header in flutter http post request

Viewed 5382

There is http package in my flutter project. I want to send a post request with custom header. Here is my code snippet. it will make clear my problem using http for custom header. It always runs else statement means the response type is not 200 and it gives me the error provided Invalid token. but on a post man, it works fine

Map data = {
    'user_fullname': _name,
    'user_address': _address,
    'user_mobile': _phone,
  };
  var tokenData = {
    'User_token': token,
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  final response = await http.post(url, body: data, headers: tokenData);
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print(response.body);
  }

Postman Testing

3 Answers

I'm guessing you're passing invalid types to the post request. (headers must be Map<String, String> (i'm not sure what is dart inferring from tokenData at runtime), body can be dynamic, etc.)

  final String url = 'YOUR_API_URL';
  final Map<String, String> tokenData = {
   "Content-type": "application/x-www-form-urlencoded",
   "user_token": token
  };
  final Map<String, String> data = { //is _phone a String?
    'user_fullname': _name,
    'user_address': _address,
    'user_mobile': _phone,
  };

  final Response response = await post(url, headers: tokenData, body: data);

  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print(response.body);
  }
}

the body can only be a String, a List<int> or a Map<String, String>

as descibed at https://pub.dev/documentation/http/latest/http/Client/post.html

A little late to this but just got the same issue. What I realised on my side is that Headers for flutter HTTP clients are case insensitive. They automatically lowercase it https://github.com/flutter/flutter/issues/16665. Some servers receive case sensitive headers.

Postman sends a case sensitive header thats why User_token is properly received.

Solution wise try :https://pub.dev/packages/alt_http

In your case must use try... catch exception.

And you can refer the below one.

import 'package:http/http.dart' as http; 

And http request is...

  var client = new http.Client();
    try{
       var response = await client.post(
         "Your Url", 
         headers: {"User_token" : token /*, ...etc*/},
         body : {
           'user_fullname': _name,
           'user_address': _address,
           'user_mobile': _phone,
         }
       );
      if(response.statusCode == 200 || response.statusCode == 201){
          //enter your code
      }
    } on Exception catch (err){
       print("Error : $err");
    }

I hope help you.

Authorization image

Related