前言:
兄弟们,网络真是个好东西,里面去个个都是人才,说话又好听,超喜欢在里面。
确实,网络已经是我们日常生活中密不可分的一部分了
那咱们今天就来讲讲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"
});
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;
const int _receiveTimeout = 15000;
const int _sendTimeout = 10000;
typedef Success<T> = Function(T data);
typedef Fail = Function(int code, String msg);
class DioUtils {
static const String TOKEN = '';
static Dio _dio;
static Dio createInstance() {
if (_dio == null) {
var options = BaseOptions(
responseType: ResponseType.json,
validateStatus: (status) {
return true;
},
baseUrl: APIs.apiPrefix,
connectTimeout: _connectTimeout,
receiveTimeout: _receiveTimeout,
sendTimeout: _sendTimeout,
);
_dio = new Dio(options);
}
return _dio;
}
static clear() {
_dio = null;
}
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) {
final NetError netError = ExceptionHandle.handleException(e);
_onError(netError.code, netError.msg, fail);
}
}
}
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 }
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学习资料~
加入我们吧,一起学习,一起进步~
|