[英]How do I set headers on Flutter/Dart http Request object?
I need a way to set the headers of the dart http Request object to application/JSON.我需要一种方法将 dart http 请求 object 的标头设置为应用程序/JSON。
I want to build a Request object to send to my backend API.我想构建一个请求 object 发送到我的后端 API。 I set the body to my JSON object, but when it gets sent, it defaults the headers to text/html instead of application/json.我将正文设置为我的 JSON object,但是当它被发送时,它默认标题为 text/html 而不是 application/json。
I have tried using the built-in method我试过使用内置方法
http.post(url,dynamic body);
but unfortunately this method places the body in the parameters of the URL and I need it in the actual body of the request.但不幸的是,这种方法将正文放在 URL 的参数中,我需要它在请求的实际正文中。
So instead I built an http Request object, and manually set the URL and body but like I said, it sets the headers to text/html.因此,我构建了一个 http 请求 object,并手动设置 URL 和正文,但就像我说的那样,它将标题设置为 text/html。 I have read the docs for https://pub.dev/documentation/http/latest/http/Request-class.html , but unfortunately, I haven't found a way to set the headers.我已经阅读了https://pub.dev/documentation/http/latest/http/Request-class.html的文档,但不幸的是,我还没有找到设置标题的方法。
postRequest(uri) async {
Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");
http.Request request = new http.Request("post", url);
request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';
var letsGo = await request.send();
print(letsGo.statusCode);
}
Much thanks for any possible solutions!非常感谢任何可能的解决方案!
Ps.附言。 this is my first ask on Stack Overflow so I apologize if I made any errors in posting.这是我在 Stack Overflow 上的第一个问题,所以如果我在发布时出现任何错误,我深表歉意。
Solved!解决了!
postRequest(uri) async {
Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");
http.Request request = new http.Request("post", url);
request.headers.clear();
request.headers.addAll({"content-type":"application/json; charset=utf-8"});
request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';
var letsGo = await request.send();
print(letsGo.statusCode);
}
I was having some issues with the Request object default setting the encoding.我在 Request object 默认设置编码时遇到了一些问题。 By manually specifying utf-8, the server I am contacting accepts it.通过手动指定 utf-8,我正在联系的服务器接受它。
for the post or get any request you can Add Header like this -
var permAddUrl = 'your requested url';
var bodyParameters = {
'Email': email,
'MobileNo': mobileNumber,
};
await http.post(
requesturl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
"Authorization":"$token",
},
body: bodyParameters,).then((response) {
var data = json.encode(response.body);
print(data);
setState(() {
if(response.statusCode == 200){
//var statesList = data['data'];
UtilAction.showSnackBar(context, " Details Submitted Successfully");
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.