优化HttpRequest

This commit is contained in:
donggang
2024-01-05 14:29:59 +08:00
parent 7b3a3877c4
commit c19c00354a

View File

@@ -6,8 +6,12 @@
*/
import { error, warn } from "cc";
var urls: any = {}; // 当前请求地址集合
var reqparams: any = {}; // 请求参数
/** 当前请求地址集合 */
var urls: any = {};
/** 请求参数 */
var reqparams: any = {};
type HttpCallback = (ret: HttpReturn) => void;
/** 请求事件 */
export enum HttpEvent {
@@ -19,9 +23,15 @@ export enum HttpEvent {
TIMEOUT = "http_request_timout"
}
/**
* HTTP请求返回值
*/
export class HttpReturn {
/** 是否请求成功 */
isSucc: boolean = false;
/** 请求返回数据 */
res?: any;
/** 请求错误数据 */
err?: any;
}
@@ -32,7 +42,7 @@ export class HttpRequest {
/** 请求超时时间 */
timeout: number = 10000;
/** 自定义请求头信息 */
header: Map<string, string> = new Map<string, string>();
private header: Map<string, string> = new Map<string, string>();
/**
* 添加自定义请求头信息
@@ -46,41 +56,17 @@ export class HttpRequest {
/**
* HTTP GET请求
* @param name 协议名
* @param completeCallback 请求完整回调方法
* @param errorCallback 请求失败回调方法
* @example
var complete = function(response){
console.log(response);
}
var error = function(response){
console.log(response);
}
oops.http.get(name, complete, error);
*/
get(name: string, completeCallback: Function, errorCallback: Function) {
this.sendRequest(name, null, false, completeCallback, errorCallback)
}
/**
* HTTP GET请求
* @param name 协议名
* @param onComplete 请求完整回调方法
* @param params 查询参数
* @param completeCallback 请求完整回调方法
* @param errorCallback 请求失败回调方法
* @example
var param = '{"uid":12345}'
var complete = function(response){
var jsonData = JSON.parse(response);
var data = JSON.parse(jsonData.Data);
console.log(data.Id);
var complete = (ret: HttpReturn) => {
console.log(ret.res);
}
var error = function(response){
console.log(response);
}
oops.http.getWithParams(name, param, complete, error);
oops.http.getWithParams(name, complete, param);
*/
getWithParams(name: string, params: any, completeCallback: Function, errorCallback: Function) {
this.sendRequest(name, params, false, completeCallback, errorCallback)
get(name: string, onComplete: HttpCallback, params: any = null) {
this.sendRequest(name, params, false, onComplete)
}
/**
@@ -95,40 +81,20 @@ export class HttpRequest {
*/
getAsync(name: string, params: any = null): Promise<HttpReturn> {
return new Promise((resolve, reject) => {
var ret: HttpReturn = new HttpReturn();
var complete = function (response: any) {
ret.isSucc = true;
ret.res = response;
this.sendRequest(name, params, false, (ret: HttpReturn) => {
resolve(ret);
}
var error = function (response: any) {
ret.isSucc = true;
ret.err = response;
resolve(ret);
}
this.sendRequest(name, params, false, complete, error)
})
});
}
/**
* HTTP GET请求非文本格式数据
* @param name 协议名
* @param completeCallback 请求完整回调方法
* @param errorCallback 请求失败回调方法
*/
getByArraybuffer(name: string, completeCallback: Function, errorCallback: Function) {
this.sendRequest(name, null, false, completeCallback, errorCallback, 'arraybuffer', false);
}
/**
* HTTP GET请求非文本格式数据
* @param name 协议名
* @param onComplete 请求完整回调方法
* @param params 查询参数
* @param completeCallback 请求完整回调方法
* @param errorCallback 请求失败回调方法
*/
getWithParamsByArraybuffer(name: string, params: any, completeCallback: Function, errorCallback: Function) {
this.sendRequest(name, params, false, completeCallback, errorCallback, 'arraybuffer', false);
getByArraybuffer(name: string, onComplete: HttpCallback, params: any = null) {
this.sendRequest(name, params, false, onComplete, 'arraybuffer', false);
}
/**
@@ -139,18 +105,9 @@ export class HttpRequest {
*/
getAsyncByArraybuffer(name: string, params: any = null): Promise<HttpReturn> {
return new Promise((resolve, reject) => {
var ret: HttpReturn = new HttpReturn();
var complete = function (response: any) {
ret.isSucc = true;
ret.res = response;
this.sendRequest(name, params, false, (ret: HttpReturn) => {
resolve(ret);
}
var error = function (response: any) {
ret.isSucc = true;
ret.err = response;
resolve(ret);
}
this.sendRequest(name, params, false, complete, error, 'arraybuffer', false);
}, 'arraybuffer', false);
});
}
@@ -158,44 +115,28 @@ export class HttpRequest {
* HTTP POST请求
* @param name 协议名
* @param params 查询参数
* @param completeCallback 请求完整回调方法
* @param errorCallback 请求失败回调方法
* @param onComplete 请求完整回调方法
* @example
var param = '{"LoginCode":"donggang_dev","Password":"e10adc3949ba59abbe56e057f20f883e"}'
var complete = function(response){
var jsonData = JSON.parse(response);
var data = JSON.parse(jsonData.Data);
console.log(data.Id);
var complete = (ret: HttpReturn) => {
console.log(ret.res);
}
var error = function(response){
console.log(response);
}
oops.http.post(name, param, complete, error);
oops.http.post(name, complete, param);
*/
post(name: string, params: any, completeCallback?: Function, errorCallback?: Function) {
this.sendRequest(name, params, true, completeCallback, errorCallback);
post(name: string, onComplete: HttpCallback, params: any = null) {
this.sendRequest(name, params, true, onComplete);
}
/**
* HTTP POST请求
* @param name 协议名
* @param params 查询参数
* @returns
*/
postAsync(name: string, params: any = null): Promise<HttpReturn> {
return new Promise((resolve, reject) => {
var ret: HttpReturn = new HttpReturn();
var complete = function (response: any) {
ret.isSucc = true;
ret.res = response;
this.sendRequest(name, params, true, (ret: HttpReturn) => {
resolve(ret);
}
var error = function (response: any) {
ret.isSucc = true;
ret.err = response;
resolve(ret);
}
this.sendRequest(name, params, true, complete, error);
});
});
}
@@ -236,23 +177,21 @@ export class HttpRequest {
* @param params(JSON) 请求参数
* @param isPost(boolen) 是否为POST方式
* @param callback(function) 请求成功回调
* @param errorCallback(function) 请求失败回调
* @param responseType(string) 响应类型
* @param isOpenTimeout(boolean) 是否触发请求超时错误
*/
private sendRequest(name: string,
params: any,
isPost: boolean,
completeCallback?: Function,
errorCallback?: Function,
onComplete: HttpCallback,
responseType?: string,
isOpenTimeout = true,
timeout: number = this.timeout) {
isOpenTimeout: boolean = true) {
if (name == null || name == '') {
error("请求地址不能为空");
return;
}
var url: string, newUrl: string, paramsStr: string;
var url: string, newUrl: string, paramsStr: string = "";
if (name.toLocaleLowerCase().indexOf("http") == 0) {
url = name;
}
@@ -271,7 +210,7 @@ export class HttpRequest {
newUrl = url;
}
if (urls[newUrl] != null && reqparams[newUrl] == paramsStr!) {
if (urls[newUrl] != null && reqparams[newUrl] == paramsStr) {
warn(`地址【${url}】已正在请求中,不能重复请求`);
return;
}
@@ -280,7 +219,7 @@ export class HttpRequest {
// 防重复请求功能
urls[newUrl] = xhr;
reqparams[newUrl] = paramsStr!;
reqparams[newUrl] = paramsStr;
if (isPost) {
xhr.open("POST", url);
@@ -302,41 +241,41 @@ export class HttpRequest {
// 请求超时
if (isOpenTimeout) {
xhr.timeout = timeout;
xhr.timeout = this.timeout;
xhr.ontimeout = () => {
this.deleteCache(newUrl);
data.event = HttpEvent.TIMEOUT;
if (errorCallback) errorCallback(data);
ret.isSucc = false;
ret.err = HttpEvent.TIMEOUT; // 超时
onComplete(data);
}
}
xhr.onloadend = (a) => {
// 响应结果
var ret: HttpReturn = new HttpReturn();
xhr.onloadend = () => {
if (xhr.status == 500) {
this.deleteCache(newUrl);
if (errorCallback == null) return;
data.event = HttpEvent.NO_NETWORK; // 断网
if (errorCallback) errorCallback(data);
ret.isSucc = false;
ret.err = HttpEvent.NO_NETWORK; // 断网
onComplete(ret);
}
}
xhr.onerror = () => {
this.deleteCache(newUrl);
if (errorCallback == null) return;
ret.isSucc = false;
if (xhr.readyState == 0 || xhr.readyState == 1 || xhr.status == 0) {
data.event = HttpEvent.NO_NETWORK; // 断网
ret.err = HttpEvent.NO_NETWORK; // 断网
}
else {
data.event = HttpEvent.UNKNOWN_ERROR; // 未知错误
ret.err = HttpEvent.UNKNOWN_ERROR; // 未知错误
}
if (errorCallback) errorCallback(data);
onComplete(ret);
};
xhr.onreadystatechange = () => {
@@ -344,39 +283,25 @@ export class HttpRequest {
this.deleteCache(newUrl);
if (xhr.status == 200) {
if (completeCallback) {
if (responseType == 'arraybuffer') {
// 加载非文本格式
xhr.responseType = responseType;
if (completeCallback) completeCallback(xhr.response);
}
else {
// 加载非文本格式
var data: any = JSON.parse(xhr.response);
if (data.code != null) {
/** 服务器错误码处理 */
if (data.code == 0) {
if (completeCallback) completeCallback(data.data);
}
else {
if (errorCallback) errorCallback(data);
}
}
else {
if (completeCallback) completeCallback(data);
}
}
if (xhr.status == 200 && onComplete) {
ret.isSucc = true;
if (responseType == 'arraybuffer') {
xhr.responseType = responseType; // 加载非文本格式
ret.res = xhr.response;
}
else {
ret.res = JSON.parse(xhr.response);
}
onComplete(ret);
}
};
// 发送请求
if (params == null || params == "") {
xhr.send();
}
else {
xhr.send(paramsStr!); // 根据服务器接受数据方式做选择
// xhr.send(JSON.stringify(params));
xhr.send(paramsStr);
}
}