在flutter中的http-post方法的主体处发送int和boolean



嗨,我有一篇作为的http帖子

final http.Response response = await client.post(
'http://someurl/',
headers: {
HttpHeaders.contentTypeHeader: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
body: {
"isItTake": false,
"servisID": 1
}
);

但当我尝试这种张贴方法时;未处理的异常:类型"bool"不是类型强制转换中类型"String"的子类型;。我可以将API更改为期望字符串,但我想知道是否有办法发送int或boolean。请注意,当我在邮递员上发送类似的请求时,一切都很好
编辑:
邮差:
POST/someendpoint/HTTP/1.1
主机:somehost
授权:令牌sometoken
内容类型:application/json
缓存控制:无缓存
邮递员令牌:20582fd0-c980-2d0d-fb2f-3bdd87d767f5\

{"isItTake":false,"服务ID":1.}

尝试将请求正文值作为字符串发送,看看是否有效。我以前遇到过http请求的请求体与类型不匹配的问题,我不太确定它为什么会抛出这样的异常,尽管api的文档明确指定了请求体中每个值的类型。试试这个:

final http.Response response = await client.post(
'http://someurl/',
headers: {
HttpHeaders.contentTypeHeader: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
body: {
"isItTake": 'false',
"servisID": '1'
}
);

或者,如果你的值在一些布尔和int变量中:

final http.Response response = await client.post(
'http://someurl/',
headers: {
HttpHeaders.contentTypeHeader: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
body: {
"isItTake": isItTake.toString(),
"servisID": servisID.toString()
}
);

使用String encoded = json.encode(theMap);,然后发布encoded。如果需要特定的字符编码(例如utf-8(,则使用utf8.encode(encoded)对字符串进行进一步编码,并发布生成的字节数组。(第二步对于utf-8来说应该是不必要的,因为我认为这是默认的。(

值得考虑的是这三种变体的作用:

  • List<int>-发送不透明字节数组
  • String使用字符编码将字符串编码为字节,并发送字节数组
  • Map<String, String>-对中的字符串键/值对进行编码CCD_ 7并发送

如果您想发送更复杂的数据,则需要将其转换为上述数据之一(服务器需要知道如何解码(。这就是content-type标头的有用之处。最终,服务器接收一个字节数组,并将其转换回,例如,一个字符串、一些json、一组表单字段或一个图像。它知道如何根据标头和任何指定的编码来实现这一点。

完整信用:来源

您可以使用"isItTake":'错误的

相关内容

最新更新