react-native-ecpei-http
v1.0.2
Published
网络库
Downloads
12
Readme
HttpYo
简介
为满足直接使用fetch进行网络请求的不足;特意封装HttpYo框架作为项目网络框架使用;主要增加了一下特性
- 1:请求拦截处理
- 2:任务派发
- 3:网络状况处理
- 4:自定义请求核心引擎
- 5:请求结果拦截处理
网络请求
import { get, post, request } from "react-native-ecpei-network"; /** * (url: string, timeout?: number) => Promise<ResponseResult> * GET 请求 */ get("http://172.18.0.201:3000/testget").then((responseRes)=>{ if(responseRes.success){ responseRes.result.json().then(()=>{ //得到数据 }) }else{ //请求失败 } }) /** * (url: string, body?: Body, headers?: Headers, timeout?: number) => Promise<ResponseResult> * POST 请求 **/ post("http://172.18.0.201:3000/testpost?test=true&my=猪猪", { id: 22121, name: "aaaa" }).then((responseRes)=>{ if(responseRes.success){ responseRes.result.json().then(()=>{ //得到数据 }) }else{ //请求失败 } }) /** * (url: string, options: any, timeout?: number) => Promise<ResponseResult> * */ request("http://172.18.0.201:3000/testget", { method:HTTPMethod.GET, params:{name:1111} }).then(()=>{ // }) /** * 原始请求 * Request 请求 */ HttpYo.request(new Request(url, HTTPMethod.POST, null, null, datas)).subscribe((res) => { if(res.isdone == true){ console.log(res) } }) /** * 获取请求进度 * get post request 无法获取进度 * */ HttpYo.request(new Request(url, HTTPMethod.POST, null, null, datas)).subscribe((res) => { if(res.isdone == false){ console.log("当前的进度为:",res.percent) }else{ //请求完成 } })
请求拦截器
系统默认增加拦截器 RequestParamsInterceptor Params参数处理器 TimeOutInterceptor 超时处理器 BodyInterceptor Body数据处理器 URLEnCodeInterceptor URL编码处理器 拦截器管理者InterceptorManager 1:增加拦截器 2:移除拦截器 3:替换拦截器 import { Interceptor, //拦截器基类 DefaultHeadersInterceptor, //增加默认请求头拦截器 LogInterceptor, //简单的日志输出 DataInterceptor, //模拟数据拦截器 InterceptorManager, //拦截器管理者 } from "react-native-ecpei-network" 使用框架提供的拦截器 function Log(msg){ //打印 } //简单的日志拦截器 InterceptorManager.addInterceptor(new LogInterceptor(Log)) 增加自己的拦截器 * 5个步骤 1:继承拦截器基类 class USerInterceptor extends Interceptor{ 2:实现必要方法 intercept(option, next) { 3:自定义处理 option.url = option.url + "xxxx" .... 4:向下回调 return next(option); } } 5:注册拦截器 InterceptorManager.addInterceptor(new USerInterceptor())
数据模拟
- 不需要网络 用于数据模拟
- 拦截网络请求 返回自定义格式的网络数据
- 不会通过响应拦截器
import { SimulateResponseResult, DataInterceptor, //模拟数据拦截器 InterceptorManager, //拦截器管理者 } from "react-native-ecpei-network" 1:继承 数据拦截器 class RypSimulateData extends DataInterceptor{ //simulateData(option: HttpRequestOptions): SimulateResponseResult | null; 2:实现对象方法 simulateData(options){ if(xxx == ooo){ let data = { msg:"请求成功", data:{ name:"xxx", age:18, date:Date.now() .... } }; 3:返回指定对象 return new SimulateResponseResult(true,null,data); } 4:无任务操作 return null; } } 5:注册请求拦截 InterceptorManager.addInterceptor(new RypSimulateData()) get(url).then((Res:SimulateResponseResult)=>{ if(Res.isSimulate){ //得到模拟数据 Res.result }else{ if(Res.success){ Res.result.json().then() }else{ // } } })
响应处理器
import { get, post, ResponseResultAction, ResponseActionManager } from "react-native-ecpei-network"; 1:继承拦截器基类 class RypJsonAction extends ResponseResultAction{ 2:是否拦截这一次Response isActive(option,response) { return true } 3:拦截 //action(result: ResponseResult): ResponseResult | Promise<ResponseResult>; async action(Res){ if(Res.success && Res.result.json){ let data = awit Res.result.json() Res.result = data; return Res; }else{ Res.result = {}; return Res } } } 注册处理器 ResponseActionManager.addAction(new RypJsonAction()) get(url).then((res)=>{ if(res.success && res.error){ //请求成功 }else{ //请求失败 } })
替换网络请求核心
import { HttpYo, Engine, HttpResponse, HttpErrorResponse } from "react-native-ecpei-network"; //核心 替换网络请求 HttpYo.resetEngine(new CustomHttpEngine()) //使用Jquery Ajax class CustomHttpEngine extends Engine { request(request) { url = request.url; return Observable.create((obs) => { let XHR = jq.ajax({ url, headers: request.headers, type: request.method, data: request.body, beforeSend: () => { var _xhr = new XMLHttpRequest() _xhr.upload.onprogress = function (event) { if (event.lengthComputable) { var percent = ((event.loaded / event.total) * 100).toFixed(2) obs.next({ isdone: false, percent, response: null }); } } return _xhr; }, success: function (data, statusText) { let response = new HttpResponse(url, XHR.getAllResponseHeaders(), XHR.status(), statusText) response.json = function () { return new Promise((resolve, reject) => { resolve(JSON.parse(data)) }) }.bind(response) response.text = function () { return new Promise((resolve, reject) => { resolve(data) }) }.bind(response) obs.next({ isdone: true, percent: 100, response }) obs.complete() }, error: (error) => { let response = new HttpErrorResponse(url, XHR.getAllResponseHeaders(), error, XHR.status(), XHR.statusText) obs.next({ isdone: true, percent: 100, response }) obs.complete() }, timeout: (error) => { let response = new HttpErrorResponse(url, XHR.getAllResponseHeaders(), error, XHR.status(), XHR.statusText) obs.next({ isdone: true, percent: 100, response }) obs.complete() } }) }) } } //替换网络请求引擎 HttpYo.resetEngine(new CustomHttpEngine())