Flutter 网络请求的三种简单实现

概述:本文主要讲解了flutter网络请求三种方式 flutter自带的HttpClient第三方库http第三方库Dio 的简单实现 GET 和 POST请求,本文是笔者学习Flutter网络模块知识总结,若有问题还望不腻赐教。

一.系统自带HttpClient

1.使用中温馨提示
1.1.导入库
1
2
import 'dart:io'; // 网络请求
import 'dart:convert'; // 数据解析
1.2.Uri的多种初始化方式
1
2
3
4
5
6
// 方法1
Uri uri = Uri(scheme: 'https', host: 'app.xxx.com', path: homeNoviceListUrl);
// 方法2
Uri uri = Uri.https('app.xxx.com', homeNoviceListUrl);
// uri方法3
Uri uri = Uri.parse(baseUrl + homeNoviceListUrl);
2.简单使用
2.1.GET请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 1.1 HttpClient - get 

void loadData_sys_get() async {
print('------loadData_sys_get--------');

var httpClient = new HttpClient();
var params = Map<String, String>();

// uri方法1
Uri uri =
Uri(scheme: 'https', host: 'app.xxx.com', path: homeNoviceListUrl);

// uri方法2
// Uri uri = Uri.https(
// 'app.xxx.com', homeNoviceListUrl);

// uri方法3
// Uri uri = Uri.parse(baseUrl + homeNoviceListUrl);

var request = await httpClient.getUrl(uri);

var headers = Map<String, String>();
headers['loginSource'] = 'IOS';
headers['useVersion'] = '3.1.0';
headers['isEncoded'] = '1';
headers['bundleId'] = 'com.xxx.xxx';

request.headers.add("loginSource", "IOS");
request.headers.add("useVersion", "3.1.0");
request.headers.add("isEncoded", "1");
request.headers.add("bundleId", "com.xxx.xxx");

var response = await request.close();
var responseBody = await response.transform(Utf8Decoder()).join();

if (response.statusCode == HttpStatus.ok) {
print('请求头:${response.headers}');

print('111请求成功代发数据为:\n $responseBody');
print('--------------');
Map data = jsonDecode(responseBody);
print('222请求成功代发数据为:\n $data');
} else {
print('\n\n\n11111==请求失败${response.statusCode}');
}
}
2.2.POST请求

注意点:请求参数需要编码后放在request中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void loadData_sys_post() async {
print('------loadData_sys_post--------');

HttpClient httpClient = new HttpClient();

// queryParameters get请求的查询参数(适用于get请求???是吗???)
// Uri uri = Uri(
// scheme: "https", host: "app.xxx.com", path: homeRegularListUrl);
// HttpClientRequest request = await httpClient.postUrl(uri);

var url = baseUrl + homeRegularListUrl;
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

// 设置请求头
request.headers.set("loginSource", "IOS");
request.headers.set("useVersion", "3.1.0");
request.headers.set("isEncoded", "1");
request.headers.set("bundleId", "com.xxx.xxx");
// Content-Type大小写都ok
request.headers.set('content-type', 'application/json');

/// 添加请求体
/// https://stackoverflow.com/questions/50278258/http-post-with-json-on-body-flutter-dart/50295533
Map jsonMap = {'currentPage': '1'};
request.add(utf8.encode(json.encode(jsonMap)));

HttpClientResponse response = await request.close();
String responseBody = await response.transform(utf8.decoder).join();
if (response.statusCode == HttpStatus.ok) {
print('请求成功');
print(response.headers);
print(responseBody);
}
}

二.请求第三方库 http

1.使用中温馨提示
1.1.添加依赖
1
2
dependencies:
http: ^0.12.0 #latest version
1.2.导入库
1
import 'package:http/http.dart' as http; //导入前需要配置
2.简单使用
2.1. GET请求
2.2.1. http - get1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void loadData_http_get() async {
print('------loadData_http_get--------');

var client = http.Client();

var uri = Uri.parse(baseUrl + homeNoviceListUrl);

http.Response response = await client.get(uri);

if (response.statusCode == HttpStatus.ok) {
print(response.body);
} else {
print('请求失败 code 码为${response.statusCode}');
}
}
2.2. http - get简便方法(链式编程)
1
2
3
4
5
6
7
8
9
10
11
12
13
void loadData_http_get_convenience() async {
print('------简便方法loadData_http_get_convenience--------');

var uri = Uri.parse(baseUrl + homeNoviceListUrl);

http.Client().get(uri).then((http.Response response) {
if (response.statusCode == HttpStatus.ok) {
print(response.body);
} else {
print('请求失败 code 码为${response.statusCode}');
}
});
}
2.2. POST请求
2.2.1. http - post
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void loadData_http_post() async {
print('------ loadData_http_post --------');

var headers = Map<String, String>();
headers["loginSource"] = "IOS";
headers["useVersion"] = "3.1.0";
headers["isEncoded"] = "1";
headers["bundleId"] = "com.xxx.xxx";
headers["loginSource"] = "IOS";
headers["Content\-Type"] = "application/json";

Map params = {'currentPage': '1'};
// 嵌套两层都可以,但是具体哪个好还有待确认????
var jsonParams = utf8.encode(json.encode(params));
// var jsonParams = json.encode(params);

var httpClient = http.Client();

var uri = Uri.parse(baseUrl + homeNoviceListUrl);

http.Response response =
await httpClient.post(uri, body: jsonParams, headers: headers);

if (response.statusCode == HttpStatus.ok) {
print(response.body);
} else {
print('请求失败 code 码���${response.statusCode}');
}
}
2.2.2. http - Post简便方法(链式编程)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

void loadData_http_post_convenience() async {
print('------ loadData_http_post --------');

var headers = Map<String, String>();
headers["loginSource"] = "IOS";
headers["useVersion"] = "3.1.0";
headers["isEncoded"] = "1";
headers["bundleId"] = "com.xxx.xxx";
headers["loginSource"] = "IOS";
headers["Content\-Type"] = "application/json";

Map params = {'currentPage': '1'};
// 嵌套两层都可以,但是具体哪个好还有待确认????
var jsonParams = utf8.encode(json.encode(params));
// var jsonParams = json.encode(params);

var httpClient = http.Client();

var url = baseUrl + homeRegularListUrl;

httpClient.post(url, body: jsonParams, headers: headers).then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
}).whenComplete(httpClient.close);
}

三.请求第三方库 Dio

1.使用中温馨提示

1.1.添加依赖
1
2
dependencies:
dio: ^2.0.11 #latest version
1.2.导入库
1
import 'package:dio/dio.dart';

2.简单使用

2.1. GET请求

注意:Dio的get请求(baseUrl都是在dio.option.baseUrl设置的) 请求头可以在dio.option上设置,也可以在新建的option上设置,新建option是可选的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void loadData_dio_get() async {
var headers = Map<String, String>();
headers['loginSource'] = 'IOS';
headers['useVersion'] = '3.1.0';
headers['isEncoded'] = '1';
headers['bundleId'] = 'com.xxx.xxx';
headers['Content-Type'] = 'application/json';

Dio dio = Dio();
dio.options.headers.addAll(headers);
dio.options.baseUrl = baseUrl;

Response response = await dio.get(homeNoviceListUrl);

if (response.statusCode == HttpStatus.ok) {
print(response.headers);
print(response.data);
}
}
2.2. POST请求

注意:

1
2
3
4
5
6
7
8
dio.options.method设置是无效
Dio dio = Dio();
dio.options.method = 'post';

办法:
新建一个Options对象,然后在发起请求的时候进行设置:
Options option = Options(method:'post');
Response response = await dio.request(homeRegularListUrl,data:{"currentPage": "1"}, options: option);
2.2.1. dio - 方式一(baseUrl都是在dio.option.baseUrl设置的)

注意:直接在 dio.options设置除methods以外的 请求头参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void loadData_dio_dioOfOptionsSetting() async {
debugPrint(
' \n post请求 ======================= 开始请求 =======================\n');
var headers = Map<String, String>();
headers['loginSource'] = 'IOS';
headers['useVersion'] = '3.1.0';
headers['isEncoded'] = '1';
headers['bundleId'] = 'com.xxx.xxx';
headers['Content-Type'] = 'application/json';

Dio dio = Dio();
dio.options.baseUrl = baseUrl;
dio.options.connectTimeout = 60000;
dio.options.receiveTimeout = 60000;
dio.options.headers.addAll(headers);
dio.options.method = 'post';

Options option = Options(method: 'post');
// Response response = await dio.request(homeRegularListUrl,
// data: {"currentPage": "1"}, options: option);

Response response = await dio.post(homeRegularListUrl,
data: {"currentPage": "1"}, options: option);

if (response.statusCode == HttpStatus.ok) {
debugPrint('请求参数: ${response.request.queryParameters}');
debugPrint(
'-------------------请求成功,请求结果如下:-----------------\n \n===请求求url: ${response.request.uri.toString()} \n \n===请求 ���: \n${response.headers} \n \n===请求结果: \n${response.data}\n');
debugPrint('-------------------请求成功,请求结果打印完毕----------------');
} else {
print('请求失败');
}
}
2.2.2. dio - 方式二(baseUrl都是在dio.option.baseUrl设置的)

注意:在新建的option上设置请求头参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void loadData_dio_newOptionSetting() async {
debugPrint(' \n======================= 开始请求 =======================\n');
var headers = Map<String, String>();
headers['loginSource'] = 'IOS';
headers['useVersion'] = '3.1.0';
headers['isEncoded'] = '1';
headers['bundleId'] = 'com.xxx.xxx';
headers['Content-Type'] = 'application/json';

Options option = Options(method: 'post');
option.connectTimeout = 60000;
option.receiveTimeout = 60000;
option.headers.addAll(headers);

Dio dio = Dio();
dio.options.baseUrl = baseUrl;

Response response = await dio.post(homeRegularListUrl,
data: {"currentPage": 1}, options: option);
// Response response = await dio.request(homeRegularListUrl,
// data: {"currentPage": 1}, options: option);

if (response.statusCode == HttpStatus.ok) {
debugPrint('请求参数: ${response.request.queryParameters}');
debugPrint(
'-------------------请求成功,请求结果如下:-----------------\n \n===请求url: ${response.request.uri.toString()} \n \n===请求 头: \n${response.headers} \n \n===请求结果: \n${response.data}\n');
debugPrint('-------------------请求成功,请求结果打印完毕----------------');
} else {
print('请求失败');
}
}
------------- End Thank For Your Reading -------------