摘自Flutter中文网:官方使用的是用dart io
中的HttpClient
发起的请求,但HttpClient
本身功能较弱,很多常用功能都不支持。我们建议您使用dio
来发起网络请求,它是一个强大易用的dart http
请求库,支持Restful API
、FormData
、拦截器
、请求取消
、Cookie管理
、文件上传/下载
……详情请查看github dio
.
这边会简单使用一下官方网络请求, 然后重点说明dio
网络的封装及使用
1.Flutter官方HttpClient网络请求
//flutter原生网络请求,简单处理get请求
_flutterReuest() async {
var httpClient = HttpClient();
try {
var uri = Uri.http('m.devapi.haoshiqi.net', '/common/index_v2');
var request = await httpClient.getUrl(uri);
var response = await request.close();
if (response.statusCode == HttpStatus.ok) {
var json = await response.transform(utf8.decoder).join();
var data = jsonDecode(json);
print(data);
}
} catch (e) {
print(e);
}
}
2.Dio网络请求的封装及使用
- 添加引用:
dependencies:
dio: ^2.1.0
- 一个简单的示例
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.google.com");
print(response);
} catch (e) {
print(e);
}
}
- 代码封装:这里处理方式是GET、POST分两个方法处理的(还有一个想法是封装一个方法,通过'POST /path',这样的方式来处理)
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
class DioHttpRequest {
//get请求
static Future<ResponseData> getReqeust(String path, [dynamic params]) async {
return _request('GET', path, params);
}
//post请求
static Future<ResponseData> postRequest(String path,
[dynamic params]) async {
return _request('POST', path, params);
}
static Future<ResponseData> _request(String method, String path,
[dynamic params]) async {
BaseOptions options = BaseOptions(
baseUrl: 'https://m.devapi.haoshiqi.net',
);
Dio dio = Dio(options);
try {
Response response;
if (method == 'POST') {
response = await dio.post(path, queryParameters: params);
}else {
response = await dio.get(path, queryParameters: params);
}
if (response.statusCode == 200) {
print(response.data);
return ResponseData.parse(response.data);
} else {
ResponseData responseData = ResponseData();
responseData.errno = response.statusCode;
responseData.errmsg = '服务器异常';
return responseData;
}
} on DioError catch (e) {
ResponseData responseData = ResponseData();
responseData.errmsg = _errmsg(e.type);
//类型判断 is
if (e.error is SocketException) {
SocketException error = e.error;
responseData.errno = error.osError.errorCode;
} else {
responseData.errno = -1;
}
return responseData;
}
}
//错误码处理
static String _errmsg(DioErrorType type) {
switch (type) {
case DioErrorType.CONNECT_TIMEOUT:
return '连接超时';
break;
case DioErrorType.SEND_TIMEOUT:
return '请求超时';
break;
case DioErrorType.RECEIVE_TIMEOUT:
return '响应超时';
break;
case DioErrorType.RESPONSE:
return '出现异常';
break;
case DioErrorType.CANCEL:
return '请求取消';
break;
default:
return '无网络';
break;
}
}
}
- 返回数据处理
//返回数据处理
class ResponseData {
String errmsg;
int errno;
int timestamp;
Map data;
static ResponseData parse(dynamic data) {
Map map;
if (data is Map) {
map = data;
}else {
map = jsonDecode(data);
}
ResponseData responseData = ResponseData();
responseData.errmsg = map['errmsg'];
responseData.errno = map['errno'];
responseData.timestamp = map['timestamp'];
responseData.data = map['data'];
return responseData;
}
}
- 使用方式
//dio网络请求(推荐)
_httpReqeust() {
var request = DioHttpRequest.getReqeust('/common/index_v2');
request.then((response) {
if (response.errno == 0) {
//成功
print('成功');
} else {
//失败
print('失败');
}
setState(() {
errmsg = 'errmsg: ${response.errmsg}';
});
});
}
Demo地址:SwiftFlutterDemo
PS:我也是初学者,如有问题,请请教!
网友评论