【发布时间】:2018-08-12 16:55:26
【问题描述】:
我试图在颤振中使用 http Dart 库执行POST 请求。但我无法找到指定请求正文的方法。有人可以举个例子吗?非常感谢
【问题讨论】:
标签: api http post dart flutter
我试图在颤振中使用 http Dart 库执行POST 请求。但我无法找到指定请求正文的方法。有人可以举个例子吗?非常感谢
【问题讨论】:
标签: api http post dart flutter
首先在你的pubspec.yamllike中指定http包
dependencies:
flutter:
sdk: flutter
http: ^0.11.3+16
然后只需导入并使用它。 最小的示例如下所示:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
static Future<Map> getData() async {
http.Response res = await http.get(url); // get api call
Map data = JSON.decode(res.body);
return data;
}
static Future<Map> postData(Map data) async {
http.Response res = await http.post(url, body: data); // post api call
Map data = JSON.decode(res.body);
return data;
}
创建http.Client并将其用于api调用
//To use Client and Send methods
http.Client client = new http.Client(); // create a client to make api calls
Future<Map> getData() async {
http.Request request = new http.Request("GET", url); // create get request
http.StreamedResponse response = await client.send(request); // sends request and waits for response stream
String responseData = await response.stream.transform(UTF8.decoder).join(); // decodes on response data using UTF8.decoder
Map data = JSON.decode(responseData); // Parse data from JSON string
return data;
}
希望有帮助!
【讨论】: