我需要从我的颤振应用程序中向API发出一个GET请求,该应用程序要求请求体为JSON (raw)。
我在Postman中用JSON请求体测试了API,它似乎运行得很好。
现在,在我的颤振应用程序中,我试图做同样的事情:
_fetchDoctorAvailability() async {
var params = {
"doctor_id": "DOC000506",
"date_range": "25/03/2019-25/03/2019" ,
"clinic_id":"LAD000404"
};
Uri uri = Uri.parse("http://theapiiamcalling:8000");
uri.replace(queryParameters: params);
var response = await http.get(uri, headers: {
"Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
HttpHeaders.contentTypeHeader: "application/json",
"callMethod" : "DOCTOR_AVAILABILITY"
});
print('---- status code: ${response.statusCode}');
var jsonData = json.decode(response.body);
print('---- slot: ${jsonData}');
}
然而,API给了我一个错误,说
{消息:缺少输入json.,状态: false}
如何为Http请求发送原始(或者更确切地说是JSON)请求体?
发布于 2019-03-25 05:52:18
uri.replace...
返回一个新的Uri
,所以您必须将它赋值给一个新变量,或者直接用于get
函数。
final newURI = uri.replace(queryParameters: params);
var response = await http.get(newURI, headers: {
"Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
HttpHeaders.contentTypeHeader: "application/json",
"callMethod" : "DOCTOR_AVAILABILITY"
});
使用员额:
var params = {
"doctor_id": "DOC000506",
"date_range": "25/03/2019-25/03/2019" ,
"clinic_id":"LAD000404"
};
var response = await http.post("http://theapiiamcalling:8000",
body: json.encode(params)
,headers: {
"Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
HttpHeaders.contentTypeHeader: "application/json",
"callMethod" : "DOCTOR_AVAILABILITY"
});
发布于 2020-02-20 04:02:09
到达
GET请求不是用来向服务器发送数据的(而是看看这个)。这就是为什么http.dart
get
方法没有body
参数的原因。但是,当您想要指定从服务器获得什么时,有时需要包含查询参数,这是一种数据形式。查询参数是键值对,因此可以将它们作为如下所示的映射:
final queryParameters = {
'name': 'Bob',
'age': '87',
};
final uri = Uri.http('www.example.com', '/path', queryParameters);
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.get(uri, headers: headers);
帖子
与GET请求不同,POST请求用于发送正文中的数据。你可以这样做:
final body = {
'name': 'Bob',
'age': '87',
};
final jsonString = json.encode(body);
final uri = Uri.http('www.example.com', '/path');
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.post(uri, headers: headers, body: jsonString);
注意,参数是Dart端的Map。然后,通过json.encode()
函数从dart:convert
库将它们转换为JSON字符串。那根绳子就是柱子的身体。
因此,如果服务器要求您在GET请求体中传递数据,请再次检查。虽然以这种方式设计服务器是可能的,但这是不标准的。
发布于 2022-08-09 22:28:35
您可以按以下方式使用请求类:
var request = http.Request(
'GET',
Uri.parse("http://theapiiamcalling:8000"),
)..headers.addAll({
"Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
HttpHeaders.contentTypeHeader: "application/json",
"callMethod": "DOCTOR_AVAILABILITY",
});
var params = {
"doctor_id": "DOC000506",
"date_range": "25/03/2019-25/03/2019",
"clinic_id": "LAD000404"
};
request.body = jsonEncode(params);
http.StreamedResponse response = await request.send();
print(response.statusCode);
print(await response.stream.bytesToString());
另外,请注意,邮递员可以使用超过15种语言的将API请求转换为代码片段。如果选择Dart,您将发现与上面类似的代码。
https://stackoverflow.com/questions/55331782
复制相似问题