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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| class BaseUrl { static const String url = 'http://127.0.0.1'; }
class HttpUtil { static void get(String url, {Map<String, dynamic> data, Map<String, dynamic> headers, Function success, Function error}) async { if (data != null && data.isNotEmpty) { StringBuffer options = new StringBuffer('?'); data.forEach((key, value) { options.write('$key=$value&'); }); String optionsStr = options.toString(); optionsStr = optionsStr.substring(0, optionsStr.length - 1); url += optionsStr; }
await _sendRequest(url, 'get', success, headers: headers, error: error); }
static void post(String url, {Map<String, dynamic> data, Map<String, dynamic> headers, Function success, Function error}) async { _sendRequest(url, 'post', success, data: data, headers: headers, error: error); }
static Future _sendRequest(String url, String method, Function success, {Map<String, dynamic> data, Map<String, dynamic> headers, Function error}) async { int _code; String _msg; var _backData;
if (!url.startsWith('http')) { url = BaseUrl.url + url; }
try { Map<String, dynamic> dataMap = data == null ? new Map() : data; Map<String, dynamic> headersMap = headers == null ? new Map() : headers;
Response response; Dio dio = new Dio(); dio.options.connectTimeout = 10000; dio.options.receiveTimeout = 3000; dio.options.headers .addAll(headersMap);
if (method == 'get') { response = await dio.get(url); } else { response = await dio.post(url, data: dataMap); }
if (response.statusCode != 200) { _msg = '网络请求错误,状态码:' + response.statusCode.toString(); _handError(error, _msg); return; }
Map<String, dynamic> resCallbackMap = response.data; _code = resCallbackMap['code']; _msg = resCallbackMap['msg']; _backData = resCallbackMap['data'];
if (success != null) { if (_code == 0) { success(_backData); } else { String errorMsg = _code.toString() + ':' + _msg; _handError(error, errorMsg); } } } catch (exception) { _handError(error, '数据请求错误:' + exception.toString()); } }
static Future _handError(Function errorCallback, String errorMsg) { if (errorCallback != null) { errorCallback(errorMsg); } return null; } }
|