34

The post request is throwing an error while setting the header map.

Here is my code

Future<GenericResponse> makePostCall(
  GenericRequest genericRequest) {String URL = "$BASE_URL/api/";

Map data = {
  "name": "name",
  "email": "email",
  "mobile": "mobile",
  "transportationRequired": false,
  "userId": 5,
};

Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};


return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
  print(res);
  if (res["code"] != 200) throw new Exception(res["message"][0]);
  return GenericResponse.fromJson(res);
});

}

but I'm getting this exception with headers.

══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1      RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)

Anybody facing this issue? I didn't find any clue with the above log.

1
  • try encoding your body to json, eg var body = json.encode({"foo": "bar"}); Commented Jun 16, 2020 at 3:53

6 Answers 6

47

Try

 Map<String, String> requestHeaders = {
       'Content-type': 'application/json',
       'Accept': 'application/json',
       'Authorization': '<Your token>'
     };
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, @Sami Kanafani, it solved my issue partially.
why partially, what is your current problem?
what if we want to pass token to headers........help will be appreciated
@SamiKanafani - thanks this solved my issue. Question though, without <String, String> my code completed, seemingly, without making the REST call - I didn't get any exceptions (unlike the example above) and there was no REST response (good or bad). What's happening under the hood that causes this?
i didn't understand much, you mean you removed <String,String> and you didn't exceptions but the request was not sent?
18

You can try this:

Map<String, String> get headers => {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer $_token",
      };

and then along with your http request for header just pass header as header

example:

Future<AvatarResponse> getAvatar() async {
    var url = "$urlPrefix/api/v1/a/me/avatar";
    print("fetching $url");
    var response = await http.get(url, headers: headers);
    if (response.statusCode != 200) {
      throw Exception(
          "Request to $url failed with status ${response.statusCode}: ${response.body}");
    }

    var avatar = AvatarResponse()
      ..mergeFromProto3Json(json.decode(response.body),
          ignoreUnknownFields: true);
    print(avatar);
    return avatar;
  }

Comments

6

I have done it this way passing a private key within the headers. This will also answer @Jaward:

class URLS {
    static const String BASE_URL = 'https://location.to.your/api';
    static const String USERNAME = 'myusername';
    static const String PASSWORD = 'mypassword';
}

In the same .dart file:

class ApiService {

    Future<UserInfo> getUserInfo() async {

      var headers = {
        'pk': 'here_a_private_key',
        'authorization': 'Basic ' +
           base64Encode(utf8.encode('${URLS.USERNAME}:${URLS.PASSWORD}')),
        "Accept": "application/json"
      };

      final response = await http.get('${URLS.BASE_URL}/UserInfo/v1/GetUserInfo',
        headers: headers);

      if (response.statusCode == 200) {
        final jsonResponse = json.decode(response.body);
        return new UserInfo.fromJson(jsonResponse);
      } else {
        throw Exception('Failed to load data!');
      }
    }
}

Comments

1

Try this

Future<String> createPost(String url, Map newPost) async {
  String collection;
  try{
    Map<String, String> headers = {"Content-type": "application/json"};
    Response response =
    await post(url, headers: headers, body: json.encode(newPost));
    String responsebody = response.body;
    final int statusCode = response.statusCode;
    if (statusCode == 200 || statusCode == 201) {
      final jsonResponse = json.decode(responsebody);
      collection = jsonResponse["token"];
    } 
    return collection;
  }
  catch(e){
    print("catch");
  }

}

Comments

1
Future<String> loginApi(String url) async {


 Map<String, String> header = new Map();
 header["content-type"] =  "application/x-www-form-urlencoded";  
header["token"] =  "token from device";  

try {
   final response = await http.post("$url",body:{
         "email":"[email protected]",
       "password":"3efeyrett"
       },headers: header);    

   Map<String,dynamic> output = jsonDecode(response.body);

        if (output["status"] == 200) {

           return "success";
        }else{
        return "error";

  } catch (e) {
    print("catch--------$e");
  return "error";
   }
return "";

}

Comments

0
 void getApi() async {
SharedPreferences prefsss = await SharedPreferences.getInstance();
String tokennn = prefsss.get("k_token");
String url = 'http://yourhost.com/services/Default/Places/List';
Map<String, String> mainheader = {
  "Content-type": "application/json",
  "Cookie": tokennn
};
String requestBody =
    '{"Take":100,"IncludeColumns":["Id","Name","Address","PhoneNumber","WebSite","Username","ImagePath","ServiceName","ZoneID","GalleryImages","Distance","ServiceTypeID"],"EqualityFilter":{"ServiceID":${_radioValue2 != null ? _radioValue2 : '""'},"ZoneID":"","Latitude":"${fav_lat != null ? fav_lat : 0.0}","Longitude":"${fav_long != null ? fav_long : 0.0}","SearchDistance":"${distanceZone}"},"ContainsText":"${_txtSearch}"}';

Response response = await post(url , headers: mainheader ,body:requestBody);
String parsedata = response.body;
var data = jsonDecode(parsedata);
var getval = data['Entities'] as List;
setState(() {
  list = getval.map<Entities>((json) => Entities.fromJson(json)).toList();
});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.