/** * Http管理器 * */ import { sys } from "cc"; import SubManager from "../../Sub/SubManager"; export class HttpManager { private static _I: HttpManager | null = null; public static get I(): HttpManager { if (!HttpManager._I) HttpManager._I = new HttpManager(); return HttpManager._I; } private constructor() {} /** * 发送请求 * @param url 接口地址 * @param data 消息字符串 (json格式) * @param method 请求方式 * @param bLock 是否锁定屏幕 * @param formData 是否formData * @returns */ public async send(url: string, data: any, method: "GET" | "POST" | "PUT" = "GET") { console.log("[Http] 请求Url:",url, " 方式:", method, " 数据:", data); var xhr = new XMLHttpRequest(); xhr.timeout = 10000; if (method == 'GET') { url = url + encodeURI(this.jsonToQueryString(data)); xhr.open(method, url, true); if (sys.isNative) { xhr.setRequestHeader("Accept-Encoding", "gzip,deflate"); xhr.setRequestHeader("content-type", "text/html;charset=utf-8"); } } else { xhr.open(method, url, true); xhr.setRequestHeader("Content-type", "application/json"); } let self = this; return new Promise((resolve, reason) => { self.quest(xhr, method, data).then(value => { resolve(value); }).catch(err => { resolve(null); }); }); } /** * 把对象转 ?a=1&b=2 的查询串 */ private jsonToQueryString(json: any) { var str = ''; if (typeof json == "object") { str = "?"; for (var k in json) { if (str != "?") { str += "&"; } str += encodeURIComponent(k) + "=" + encodeURIComponent(json[k]); } } return str; } /** * 统一封装 XHR 的发送与状态回调 */ private async quest(xhr: XMLHttpRequest, method: "GET" | "POST" | "PUT" = "GET", data: Object) { return new Promise((resolve, reason) => { xhr.onreadystatechange = () => { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300) { console.log("[Http] 返回", xhr.response); try { resolve(JSON.parse(xhr.response)); } catch (e) { reason(e); } } else { reason(xhr.status) } } }; xhr.onerror = (error) => { console.error("http request onerror"); SubManager.ShowPrompt("网络错误,请检查网络连接"); reason(error) }; xhr.ontimeout = (e) => { console.error("http request timeout"); SubManager.ShowPrompt("网络错误,请检查网络连接"); reason(e) } //根据POST和GET方式,选择是否发送msg数据 if (method == 'POST') { xhr.send(JSON.stringify(data)); } else if (method == 'PUT') { xhr.send(JSON.stringify(data)); } else { xhr.send(); } }); } }