前言:
兄弟們,網路真是個好東西,里面去個個都是人才,說話又好聽,超喜歡在里面,

確實,網路已經是我們日常生活中密不可分的一部分了
那咱們今天就來講講Flutter里的網路,
本節內容:
1.Dart 原生的網路請求 HttpClient
2.第三方網路請求 http
3.Flutter 發布的 dio (這個可是不得了)

1.Dart 原生的網路請求 HttpClient
對于初學者來說,使用dart 中的HttpClient發起的請求,能快速接入HTTP網路請求,
但HttpClient本身功能較弱,很多常用功能都不支持,
第一步:匯入dart:io包
import 'dart:io';
第二步:創建一個HttpClient
HttpClient httpClient = new HttpClient();
該 httpClient支持常用的HTTP操作: such as GET, POST, PUT, DELETE.
第三步:打開Http連接,設定請求頭
Uri uri=Uri(scheme: "https", host: "flutterchina.club", queryParameters: {
"userName":"chen",
"password":"123456"
}); //在這里可以設定比如 Get 請求、Post 請求、Delete 請求
HttpClientRequest request = await httpClient.getUrl(uri);
第四步:等待連接服務器(異步請求哦)
HttpClientResponse response = await request.close();
第五步:讀取回應內容
if (response.statusCode == HttpStatus.ok) {
_content = await response.transform(Utf8Decoder()).join();
}
第六步:斷開連接
httpClient.close();
這是最簡單的方法,但是過于麻煩,還有 Cookie 的管理也是比較困難的
2.第三方網路請求 http
第一步:安裝 http
參考:https://pub.flutter-io.cn/packages/http
http: ^0.12.2
在pubspec.yaml中配置保存后,記得put get~
Get 請求
void getRequest() async {
var client = http.Client();
http.Response response = await client.get(url_2);
_content = response.body;
}
Post 請求
void postRequest() async {
var params = Map<String, String>();
params["username"] = "hellonews";
params["password"] = "123456";
var client = http.Client();
var response = await client.post(url_post, body: params);
_content = response.body;
}
其實說了這么多作用不大,畢竟開發追求的效率
之間上壓軸好戲!!!
3.dio請求
官網最新版和檔案:https://pub.flutter-io.cn/packages/dio
dependencies:
dio: ^4.0.0
咱們先來一個簡單的例子
import 'package:dio/dio.dart';
void main() async {
var dio = Dio();
final response = await dio.get('https://www.baidu.com');
print(response.data);
}
這樣肯定是不符合我們的開發日常需求的
我們來進行封裝
dio的封裝:
記得自己把包匯入啊!!!,本節使用的是4.0.0的dio版本~
const int _connectTimeout = 15000; //15s
const int _receiveTimeout = 15000;
const int _sendTimeout = 10000;
typedef Success<T> = Function(T data);
typedef Fail = Function(int code, String msg);
class DioUtils {
// default options
static const String TOKEN = '';
static Dio _dio;
// 創建 dio 實體物件
static Dio createInstance() {
if (_dio == null) {
/// 全域屬性:請求前綴、連接超時時間、回應超時時間
var options = BaseOptions(
/// 請求的Content-Type,默認值是"application/json; charset=utf-8".
/// 如果您想以"application/x-www-form-urlencoded"格式編碼請求資料,
/// 可以設定此選項為 `Headers.formUrlEncodedContentType`, 這樣[Dio]就會自動編碼請求體.
// contentType: Headers.formUrlEncodedContentType, // 適用于post form表單提交
responseType: ResponseType.json,
validateStatus: (status) {
// 不使用http狀態碼判斷狀態,使用AdapterInterceptor來處理(適用于標準REST風格)
return true;
},
baseUrl: APIs.apiPrefix,
// headers: httpHeaders,
connectTimeout: _connectTimeout,
receiveTimeout: _receiveTimeout,
sendTimeout: _sendTimeout,
);
_dio = new Dio(options);
}
return _dio;
}
// 清空 dio 物件
static clear() {
_dio = null;
}
// 請求,回傳引數為 T
// method:請求方法,Method.POST等
// path:請求地址
// params:請求引數
// success:請求成功回呼
// error:請求失敗回呼
static Future request<T>(Method method, String path, dynamic params,
{Success success, Fail fail}) async {
try {
//沒有網路
var connectivityResult = await (new Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
_onError(ExceptionHandle.net_error, '網路例外,請檢查你的網路!', fail);
return;
}
Dio _dio = createInstance();
Response response = await _dio.request(path,
data: params, options: Options(method: MethodValues[method]));
if (response != null) {
if (success != null) {
success(response.data);
}
} else {
_onError(ExceptionHandle.unknown_error, '未知錯誤', fail);
}
} on DioError catch (e) {
// LogUtils.print_('請求出錯:' + e.toString());
final NetError netError = ExceptionHandle.handleException(e);
_onError(netError.code, netError.msg, fail);
}
}
}
/// 自定義Header
Map<String, dynamic> httpHeaders = {
'Accept': 'application/json,*/*',
'Content-Type': 'application/json',
'token': DioUtils.TOKEN
};
void _onError(int code, String msg, Fail fail) {
if (code == null) {
code = ExceptionHandle.unknown_error;
msg = '未知例外';
}
LogUtils.print_('介面請求例外: code: $code, msg: $msg');
if (fail != null) {
fail(code, msg);
}
}
Map<String, dynamic> parseData(String data) {
return json.decode(data) as Map<String, dynamic>;
}
enum Method { GET, POST, DELETE, PUT, PATCH, HEAD }
//使用:MethodValues[Method.POST]
const MethodValues = {
Method.GET: "get",
Method.POST: "post",
Method.DELETE: "delete",
Method.PUT: "put",
Method.PATCH: "patch",
Method.HEAD: "head",
};
網路例外處理:
import 'dart:io';
import 'package:dio/dio.dart';
class ExceptionHandle {
static const int success = 200;
static const int success_not_content = 204;
static const int unauthorized = 401;
static const int forbidden = 403;
static const int not_found = 404;
static const int net_error = 1000;
static const int parse_error = 1001;
static const int socket_error = 1002;
static const int http_error = 1003;
static const int timeout_error = 1004;
static const int cancel_error = 1005;
static const int unknown_error = 9999;
static NetError handleException(DioError error) {
if (error is DioError) {
if (error.type == DioErrorType.DEFAULT ||
error.type == DioErrorType.RESPONSE) {
dynamic e = error.error;
if (e is SocketException) {
return NetError(socket_error, '網路例外,請檢查你的網路!');
}
if (e is HttpException) {
return NetError(http_error, '服務器例外!');
}
if (e is FormatException) {
return NetError(parse_error, '資料決議錯誤!');
}
return NetError(net_error, '網路例外,請檢查你的網路!');
} else if (error.type == DioErrorType.CONNECT_TIMEOUT ||
error.type == DioErrorType.SEND_TIMEOUT ||
error.type == DioErrorType.RECEIVE_TIMEOUT) {
// 連接超時 || 請求超時 || 回應超時
return NetError(timeout_error, '連接超時!');
} else if (error.type == DioErrorType.CANCEL) {
return NetError(cancel_error, '取消請求');
} else {
return NetError(unknown_error, '未知例外');
}
} else {
return NetError(unknown_error, '未知例外');
}
}
}
class NetError {
int code;
String msg;
NetError(this.code, this.msg);
}
完成啦,有疑問的話請添加我的練習方式哦~

歡迎留言糾正 ~ 不妨給個點贊哈哈
我是阿T一個幽默的程式員 我們下期再見~
添加我為你的好友,領取原始碼以及Flutter學習資料~

加入我們吧,一起學習,一起進步~

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/290124.html
標籤:其他
