文章将会被同步至微信公众号:Android部落格
文章参考:https://flutterchina.club/networking/
文章参考:https://flutter.dev/docs/cookbook/networking/fetch-data
一、flutter中网络请求使用http库
在pubspec.yaml中添加配置:
dependencies:
http: ^0.12.0
在工程的代码中添加引用:
import 'package:http/http.dart' as http;
1)post请求:
_getData() async {
var url = "http://example.com/whatsit/create";
http.post(url, body: {"name": "doodle", "color": "blue"})
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
}
2)get请求:
_getData() async {
var url1 = "https://jsonplaceholder.typicode.com/posts/1";
http.get(url1).then((response) {
print("Response status1: ${response.statusCode}");
print("Response body1: ${response.body}");
});
}
还可以直接读取server上的文件:
http.read("http://example.com/foobar.txt").then(print);
3)针对一次请求多个域名,可以连续请求:
var client = new http.Client();
client.post(
"http://example.com/whatsit/create",
body: {"name": "doodle", "color": "blue"})
.then((response) => client.get(response.body['uri']))
.then((response) => print(response.body))
.whenComplete(client.close);
另外针对部分请求需要自定义头信息,可以通过继承BaseClient:
class UserAgentClient extends http.BaseClient {
final String userAgent;
final http.Client _inner;
UserAgentClient(this.userAgent, this._inner);
Future<StreamedResponse> send(BaseRequest request) {
request.headers['user-agent'] = userAgent;
return _inner.send(request);
}
}
二、使用httpClient
var url = 'https://jsonplaceholder.typicode.com/posts';
var httpClient = new HttpClient();
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(utf8.decoder).join();
List data = jsonDecode(json);
if (data.isNotEmpty) {
for (Map tempData in data) {
JsonData resultData = JsonData.fromJson(tempData);
result = resultData.body ?? "出错了";
print("result is:" + result);
}
}
}
} catch (exception) {
print("result is:" + exception.toString());
}
对于需要填充头信息的请求方式如下:
get() async {
var httpClient = new HttpClient();
var uri = new Uri.http(
'example.com', '/path1/path2', {'param1': '42', 'param2': 'foo'});
var request = await httpClient.getUrl(uri);
var response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
}
对于post请求有两个接口:
httpClient.post(host, port, path)
httpClient.postUrl(url)
请求到的数据可以使用json库解析。
微信公众号二维码: