概述:本文主要講解了flutter網路請求三種方式 flutter自帶的HttpClient、 第三方庫http 和 第三方庫Dio 的簡單實現 GET 和 POST請求,本文是筆者學習Flutter網路模組知識總結,若有問題還望不膩賜教。
一.系統自帶HttpClient
1.使用中溫馨提示
1.1.匯入庫
import 'dart:io'; // 網路請求
import 'dart:convert'; // 資料解析
複製程式碼
1.2.Uri的多種初始化方式
// 方法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.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中
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.新增依賴
dependencies:
http: ^0.12.0 #latest version
複製程式碼
1.2.匯入庫
import 'package:http/http.dart' as http; //匯入前需要配置
複製程式碼
2.簡單使用
2.1. GET請求
2.2.1. http - get1
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簡便方法(鏈式程式設計)
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
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簡便方法(鏈式程式設計)
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.新增依賴
dependencies:
dio: ^2.0.11 #latest version
複製程式碼
1.2.匯入庫
import 'package:dio/dio.dart';
複製程式碼
2.簡單使用
2.1. GET請求
注意:Dio的get請求(baseUrl都是在dio.option.baseUrl設定的) 請求頭可以在dio.option上設定,也可以在新建的option上設定,新建option是可選的
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請求
注意:
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以外的 請求頭引數
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上設定請求頭引數
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('請求失敗');
}
}
複製程式碼