Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
颤振http头_Http_Dart_Http Headers_Flutter - Fatal编程技术网

颤振http头

颤振http头,http,dart,http-headers,flutter,Http,Dart,Http Headers,Flutter,设置标头映射时,post请求抛出错误 这是我的密码 Future<GenericResponse> makePostCall( GenericRequest genericRequest) {String URL = "$BASE_URL/api/"; Map data = { "name": "name", "email": "email", "mobil

设置标头映射时,
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);
});

}
Future makepostall(
GenericRequest GenericRequest){String URL=“$BASE_URL/api/”;
地图数据={
“名称”:“名称”,
“电子邮件”:“电子邮件”,
“移动”:“移动”,
“运输要求”:错误,
“用户ID”:5,
};
Map userHeader={“内容类型”:“应用程序/json”,“接受”:“应用程序/json”};
return _netUtil.post(URL,body:data,headers:userHeader){
印刷品(res);
如果(res[“code”!=200)抛出新异常(res[“message”][0]);
返回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)
══╡ 用手势捕捉异常╞═
颤振:处理手势时抛出以下断言:
颤振:类型“\u InternalLinkedHashMap”不是类型“Map”的子类型
颤振:
颤振:要么断言表明框架本身存在错误,要么我们应该提供
颤振:此错误消息中的更多信息可帮助您确定并修复根本原因。
颤振:无论哪种情况,请在GitHub上提交一个bug来报告这一断言:
颤振:https://github.com/flutter/flutter/issues/new?template=BUG.md
颤振:
颤振:抛出异常时,这是堆栈:
颤振:0 NetworkUtil.post1(包:saranam/network/network\u util.dart:50:41)
flatter:#1 RestDatasource.bookPandit(包:saranam/network/rest_data_source.dart:204:21)
有人面临这个问题吗?我在上面的日志中没有找到任何线索。

试试看

 Map<String, String> requestHeaders = {
       'Content-type': 'application/json',
       'Accept': 'application/json',
       'Authorization': '<Your token>'
     };
Map requestHeaders={
“内容类型”:“应用程序/json”,
“接受”:“应用程序/json”,
“授权”:“
};

我这样做是通过在头中传递私钥。这也将回答@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!');
      }
    }
}
class服务{
未来的getUserInfo()异步{
变量头={
“pk”:“这里有私钥”,
“授权”:“基本”+
base64Encode(utf8.encode(“${url.USERNAME}:${url.PASSWORD}”),
“接受”:“应用程序/json”
};
最终响应=等待http.get(“${URL.BASE_URL}/UserInfo/v1/GetUserInfo”,
标题:标题);
如果(response.statusCode==200){
final jsonResponse=json.decode(response.body);
返回新的UserInfo.fromJson(jsonResponse);
}否则{
抛出异常('加载数据失败!');
}
}
}
您可以尝试以下方法:

Map<String, String> get headers => {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer $_token",
      };
Map-get-headers=>{
“内容类型”:“应用程序/json”,
“接受”:“应用程序/json”,
“授权”:“持票人$\u代币”,
};
然后,在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;
  }
Future getAvatar()异步{
var url=“$urlPrefix/api/v1/a/me/avatar”;
打印(“获取$url”);
var response=wait http.get(url,headers:headers);
如果(response.statusCode!=200){
抛出异常(
“对$url的请求失败,状态为${response.statusCode}:${response.body}”);
}
var avatar=AvatarResponse()
…mergeFromProto3Json(json.decode(response.body),
忽略未知字段:true);
印刷品(化身);
返回化身;
}
试试这个

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

}
Future createPost(字符串url,映射newPost)异步{
字符串集合;
试一试{
映射头={“内容类型”:“应用程序/json”};
回应=
wait post(url,headers:headers,body:json.encode(newPost));
字符串responsebody=response.body;
最终int statusCode=response.statusCode;
如果(状态代码==200 | |状态代码==201){
final jsonResponse=json.decode(responsebody);
collection=jsonResponse[“token”];
} 
回收;
}
捕获(e){
打印(“捕获”);
}
}
Future loginApi(字符串url)异步{
映射头=新映射();
标题[“内容类型”]=“应用程序/x-www-form-urlencoded”;
标题[“令牌”]=“来自设备的令牌”;
试一试{
最终响应=等待http.post($url),正文:{
“电子邮件”:test@test.com",
“密码”:“3efeyrett”
},标题:标题);
映射输出=jsonDecode(response.body);
如果(输出[“状态”]==200){
返回“成功”;
}否则{
返回“错误”;
}捕获(e){
打印(“捕获--------$e”);
返回“错误”;
}
返回“”;
}
void getApi()异步{
SharedReferences Prefss=等待SharedReferences.getInstance();
字符串tokennn=prefss.get(“k_令牌”);
字符串url='0http://yourhost.com/services/Default/Places/List';
映射主标题={
“内容类型”:“应用程序/json”,
“Cookie”:tokennn
};
字符串请求体=
“{”Take“:100,”IncludeColumns:“[“Id”,“名称”,“地址”,“电话号码”,“网站”,“用户名”,“图像路径”,“服务名称”,“区域Id”,“GalleryImage”,“距离”,“服务类型Id”],“EqualityFilter:“{”服务Id:${U radioValue2!=null?{U radioValue2:“,”,“区域Id:“纬度”:“${fav_lat!=null?fav_lat:0.0}”,“经度”:”${fav_long!=null?fav_long:0.0},“搜索距离”:“${distanceZone}”,ContainsText:“${txtSearch}”;
Response-Response=wait-post(url,headers:mainheader,body:requestBody);
字符串parsedata=response.body;
var data=jsonDecode(parsedata);
var getval=数据['Entities']作为列表;
设置状态(){
list=getval.map((json)=>Entities.fromJson(json)).toList();
});
}

谢谢,@Sami Kanafani,它部分解决了我的问题。为什么部分解决,您当前的问题是什么?如果我们想将令牌传递给标头,该怎么办……。将提供帮助appreciated@SamiKanafani-谢谢,这解决了我的问题。不过问题是,在没有
的情况下,我的代码完成了,似乎没有进行REST调用-我没有收到任何异常(与上面的例子不同)并且没有休息反应(好的或坏的)。引擎盖下发生了什么导致了这种情况?我不太明白,你的意思是你删除了
,你没有例外
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 "";
 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();
});
}