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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| import 'dart:async'; import 'package:http/http.dart' as http;
import 'dart:convert';
class Api { static const String BaseUrl ="http://www.wanandroid.com/"; }
class HttpUtil { static const String GET = "get"; static const String POST = "post"; static void get(String url, Function callback, {Map<String, String> params, Map<String, String> headers, Function errorCallback}) async { if (!url.startsWith("http")) { url = Api.BaseUrl + url; } if (params != null && params.isNotEmpty) { StringBuffer sb = new StringBuffer("?"); params.forEach((key, value) { sb.write("$key" + "=" + "$value" + "&"); }); String paramStr = sb.toString(); paramStr = paramStr.substring(0, paramStr.length - 1); url += paramStr; } await _request(url, callback, method: GET, headers: headers, errorCallback: errorCallback); }
static void post(String url, Function callback, {Map<String, String> params, Map<String, String> headers, Function errorCallback}) async { if (!url.startsWith("http")) { url = Api.BaseUrl + url; } await _request(url, callback, method: POST, headers: headers, params: params, errorCallback: errorCallback); }
static Future _request(String url, Function callback, {String method, Map<String, String> headers, Map<String, String> params, Function errorCallback}) async { String errorMsg; int errorCode; var data; try { Map<String, String> headerMap = headers == null ? new Map() : headers; Map<String, String> paramMap = params == null ? new Map() : params;
http.Response res; if (POST == method) { res = await http.post(url, headers: headerMap, body: paramMap); } else { res = await http.get(url, headers: headerMap); }
if (res.statusCode != 200) { errorMsg = "网络请求错误,状态码:"+res.statusCode.toString();
_handError(errorCallback, errorMsg); return; }
Map<String, dynamic> map = json.decode(res.body);
errorCode = map['errorCode']; errorMsg = map['errorMsg']; data = map['data'];
if (callback != null) { if (errorCode >= 0) { callback(data); } else { _handError(errorCallback, errorMsg); } } } catch (exception) { _handError(errorCallback, exception.toString()); } }
static void _handError(Function errorCallback,String errorMsg){ if (errorCallback != null) { errorCallback(errorMsg); } print("errorMsg :"+errorMsg); } }
|