Flutter http headers

泄露秘密 提交于 2020-01-24 03:40:06

问题


The post request throwing 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' is not a subtype of type 'Map' 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

 Map<String, String> requestHeaders = {
       'Content-type': 'application/json',
       'Accept': 'application/json',
       'Authorization': '<Your token>'
     };



回答2:


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



回答3:


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



回答4:


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

}


来源:https://stackoverflow.com/questions/53299447/flutter-http-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!