dart - 如何在 Dart 中发出网络请求并返回一个 json 对象
问题描述
发出网络请求对 Python 来说很容易,而让这个请求变得容易的是那个sync
请求。
在 Dart 中,我可以提出这样的请求:
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
.then((HttpClientRequest request) {
// Optionally set up headers...
// Optionally write to the request object...
// Then call close.
...
return request.close();
})
.then((HttpClientResponse response) {
// Process the response.
...
});
显然这是异步请求。在我看来,上面的代码可以重复使用很多次。所以我想发出一个请求并返回一个 JSON 对象。
getResponse(String url) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));
HttpClientResponse response = await request.close();
String responseBody = await response.transform(utf8.decoder).join();
Map jsonResponse = jsonDecode(responseBody) as Map;
httpClient.close();
return jsonResponse;
}
如您所见,上述方法getResponse
返回Future<dynamic>
. 那么如何调用它并获取 json 值呢?
解决方案
要从 Future 内部获取动态,请执行以下操作之一:
// option 1 async method
MyAsyncMethod() async {
dynamic result = await getResponse("http://google.com");
if (result is Map) {
// process the data
}
}
// option 2 callback with .then()
MyNonAsyncMethod() {
getResponse("http://google.com").then ( (dynamic result) {
if (result is Map) {
// process the data
}
});
}
请注意,您自己的异步方法也可以返回 aFuture<something>
并在调用时以相同的两种方式处理。
其中 map 是嵌套的Map<String, Dynamic>
,而 result 是您创建的符合 Json 序列化接口的类型的对象(请参阅此链接)。
要访问地图中的数据:
//given example json structure
var map = {
"myPropertyName":50,
"myArrayProperty":[
"anArrayEntry"
],
"mySubobject": {
"subObjectProperty":"someValue"
}
};
var myProperty = map["myPropertyName"]; // get a property value from the object
var myArrayEntry = map["myArrayProperty"][0]; // get first element of an array property
var mySubobjectPropertyValue = map["mySubobject"]["subObjectProperty"]; // get a property value from a subobject
推荐阅读
- python - 有没有办法将 CNN 的结果传递给另一个?
- google-apps-script - 谷歌表如何确保在使用按钮运行脚本之前完成字段更改
- mpi - 在 MPI 中使用 Scatter 和 Gather 进行图像平滑
- c# - aspnetcore - 如何在“配置”方法中访问注入?
- arduino - ESP32、ESP8266 和 ESP8266 节点 MCU 不工作
- python - 带有 Scrapy Python 的 CSS 选择器 HTML
- python - Python tkinter 保存和更改 txt 文件
- vba - 如何处理损坏的表链接上的错误
- c++ - 在同一窗口中绘制 3d 和 2d 无法正常工作 openGl
- laravel - 我可以在哪里更改 FCM 网络通知点击操作网址?