颤振 http 标头

Posted

技术标签:

【中文标题】颤振 http 标头【英文标题】:Flutter http headers 【发布时间】:2019-04-17 08:59:48 【问题描述】:

post 请求在设置标头映射时抛出错误。

这是我的代码

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


但我在标题中遇到了这个异常。

══╡ 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)

有人遇到这个问题吗?上面的日志我没有找到任何线索。

【问题讨论】:

尝试将你的 body 编码为 json,例如 var body = json.encode("foo": "bar"); 【参考方案1】:

试试

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

【讨论】:

谢谢@Sami Kanafani,它部分解决了我的问题。 为什么是部分,你目前的问题是什么? 如果我们想将令牌传递给标头怎么办............我们将不胜感激 @SamiKanafani - 谢谢这解决了我的问题。不过问题是,如果没有&lt;String, String&gt;,我的代码似乎完成了,没有进行 REST 调用——我没有得到任何异常(与上面的示例不同),也没有 REST 响应(好或坏)。导致这种情况的幕后原因是什么? 我不太明白,你的意思是你删除了&lt;String,String&gt;,你没有例外但请求没有发送?【参考方案2】:

你可以试试这个:

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

然后连同您对标头的 http 请求一起将标头作为标头传递

示例:

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】:

我已经通过这种方式在标题中传递了一个私钥。这也将回答@Jaward:

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

在同一个 .dart 文件中:

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】:

试试这个

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


【讨论】:

【参考方案5】:
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":"test@test.com",
       "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 "";

【讨论】:

【参考方案6】:
 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();
);

【讨论】:

以上是关于颤振 http 标头的主要内容,如果未能解决你的问题,请参考以下文章

在颤振代码中添加授权标头会返回错误响应,而相同的请求在邮递员中工作正常

如何在颤振集成测试中模拟 http 请求?

颤振 - android - http.get 在发布模式下永远不会返回

颤振从单元\小部件测试调用http请求而不进行模拟

使用颤振时Http请求没有得到响应

如何使用颤振 http 包设置基本 url 类?