App開發(fā)之網(wǎng)絡(luò)層搭建
網(wǎng)絡(luò)層是客戶端與服務(wù)器通信的核心,本app開發(fā)大部分用到的是post請求。

服務(wù)器端
utils目錄下封裝rotesutil.js,主要是對請求與返回的二次封裝
var ResJson = function(){this.code;this.data;this.errmsg ;}module.exports ={/*** 返回錯誤*/resError:function(res,err){console.error(err)var resjson = new ResJson();resjson.code = 1;resjson.errmsg = err;res.json(resjson)},/*** 返回成功*/resSuccess:function(res,data){var resjson = new ResJson();resjson.code = 0;resjson.data = data;console.log('---res succes--- data:',data)res.json(resjson)},/*** 打印*/logReq:function(req){// console.log(req.hostname)// console.log(req.ip)// console.log(req.protocol)// console.log(req.method)// console.log('url:'+req.originalUrl+' body:'+JSON.stringify(req.body));var log = '---hostname:'+req.hostname+' ip:'+req.ip;// console.log(log)log = '---'+req.method+'_'+req.originalUrl;console.log(log)var log = '---body:'+JSON.stringify(req.body);console.log(log)}}
以發(fā)送驗證碼為例,首先在router目錄下創(chuàng)建user.js,并且在app.js中注冊這個路由
user.js文件中部分代碼
var ru = require(_roomdir + 'utils/routersutil');/*** 請求驗證碼*/router.post('/validate', function(req, res, next) {try {ru.logReq(req);var phone = req.body.phone;var country_code = req.body.country_code;var type = req.body.type;if (!phone || !type || !country_code) {ru.resError(res, '參數(shù)錯誤');} else if (!utils.checkPhone(phone)) {ru.resError(res, '請?zhí)顚懻_的手機(jī)號格式');} else {????????????/***此處為驗證碼服務(wù)器邏輯,因為本篇介紹網(wǎng)絡(luò)層,所以忽略***/????????????ru.resSuccess(res, validate);????????}} catch (err) {ru.resError(res, err.message);????}});
app.js文件中部分代碼
var userRouter = require('./routes/user');app.use('/user', userRouter);
客戶端
network目錄下,對網(wǎng)絡(luò)請求進(jìn)行封裝
chttp.dart部分代碼,主要是封裝post請求,定義協(xié)議
static?String?BASE_URL?=?'http://xxx.xxx.x.x:xxxx/';static String USER_VALIDATE = 'user/validate';static post(String url, Function successCallback,{Map<String, dynamic> params,Function errorCallback,Function completeCallback}) async {StringBuffer sb = new StringBuffer("");if (params != null) {params.forEach((key, value) {sb.write("$key" + "=" + "$value" + "&");});}String paramStr = sb.toString();if (paramStr.length > 0) {paramStr = paramStr.substring(0, paramStr.length - 1);}LogUtil.e(url,tag: Tag.TAG_CHTTP);LogUtil.e(paramStr,tag: Tag.TAG_CHTTP);BaseOptions options = new BaseOptions(baseUrl: CHttp.BASE_URL,connectTimeout: 10000,receiveTimeout: 10000,contentType: Headers.jsonContentType,responseType: ResponseType.json);Dio dio = new Dio(options);try {Response response = await dio.post(url, data: params);LogUtil.v('---url :${url}', tag: Tag.TAG_CHTTP);LogUtil.v('---paramStr :${paramStr}', tag: Tag.TAG_CHTTP);LogUtil.v('---data :${response.data}', tag: Tag.TAG_CHTTP);if (response.data['code'] == 0) {if (successCallback != null) {successCallback(response.data['data']);}if (completeCallback != null) {completeCallback();}} else {if (errorCallback != null) {errorCallback(response.data['errmsg']);}if (completeCallback != null) {completeCallback();}}} catch (e) {LogUtil.e(url, tag: Tag.TAG_CHTTP);LogUtil.e(e, tag: Tag.TAG_CHTTP);if (errorCallback != null) {errorCallback(e.toString());}if (completeCallback != null) {completeCallback();}}}
params.dart對請求參數(shù)封裝,創(chuàng)建基礎(chǔ)Params,包含基礎(chǔ)的信息,可以包括系統(tǒng),手機(jī)型號,ip等等,我們只寫了系統(tǒng)
///base paramsabstract class Params{String os;Params(){// LogUtil.e('---Params');if(Platform.isIOS){os = 'ios';}if(Platform.isAndroid){os = 'android';}if(Platform.isMacOS){os = 'macos';}if(Platform.isWindows){os = 'windows';}}Map<String, dynamic> toJson();}
驗證碼實例
///請求驗證碼class PUserVerifyCode extends Params{String country_code;String phone ;int type ;//1 注冊 2 忘記 3 修改PUserVerifyCode(country_code,phone,type){this.country_code = country_code;this.phone = phone;this.type = type;}//dynamicMap<String, String> toJson() =>{'country_code':country_code,'phone': phone,'type':type.toString(),'os':os,};}
resdata.dart對返回數(shù)據(jù)的封裝處理
同樣可以有一個基礎(chǔ)Res
abstract class Res{}
驗證碼返回數(shù)據(jù)實例
class ResUserVerifyCode extends Res{String phone;int type;String code;int time;int max ;ResUserVerifyCode.fromJson(Map<String, dynamic> json){phone = json['phone'];type = int.parse(json['type']);code = json['code'];time = json['time'];max = json['time'];}String toString() {var to_json = {'phone':phone,'type':type,'code':code,'time':time,'max':max,};String to_str = json.encode(to_json);return to_str;}}
客戶端發(fā)送驗證碼實例
///請求驗證碼 verifycode_reqVerifyCode() {CHttp.post(CHttp.USER_VALIDATE,(data) {ResUserVerifyCode resUserVerifyCode =ResUserVerifyCode.fromJson(data);if (!mounted) {return;}??????????/***客戶端處理驗證碼邏輯***/},params: PUserVerifyCode(country_code, phoneController.text, 1).toJson(),errorCallback: (err) {ToastUtil.showToast(context, err);});}
至此,服務(wù)客戶端的網(wǎng)絡(luò)層搭建基本完成,然后就是針對不同功能制定協(xié)議,編寫客戶端服務(wù)器協(xié)議。
評論
圖片
表情
