我试图在flutter中使用 http Dart库执行POST
请求。但我无法找到指定请求正文的方法。有人可以帮忙举个例子吗?非常感谢你
答案 0 :(得分:13)
首先在http
中指定pubspec.yaml
个包
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;
}
希望有所帮助!