import { _decorator, sys } from "cc"; import { SDKManager } from "../Channel/SDKManager"; import GlobalValue from "./GlobalValue"; import li_EventManager from "./li_EventManager"; import Utils from "./Utils"; import { InnerMsgCode } from "../Config/InnerMsgCode"; // import { EventManager, EventNameEnum } from "../manager/eventManager"; // import GlobalValue from "../manager/GlobalValue"; // import { DataManager } from "../manager/dataManager"; // import { SDKManager } from "../manager/sdkManager"; // import GlobalValue from "../global/GlobalValue"; const { ccclass, property } = _decorator; /** * http通讯 */ @ccclass export default class HttpUnit { // static readonly ServerHttpHost = "https://bls.vip.hnhxzkj.com/"; static readonly ServerHttpHost = "https://xqmnyx.vip.hnhxzkj.com/api/"; static PlayerToken = ""; //登录时获取的token static LoginState = 0; //登录状态 0未登录 1登录中 2已登录 static UserInfo:any = {}; //用户数据 static SerSetting:any = {}; //后台设置 //单例 private static I: HttpUnit; public static get ins(): HttpUnit { if (this.I == null) { this.I = new HttpUnit(); } return this.I; } public constructor() { } public jsonToQueryString(json: any) { var str = ''; if (typeof json == "object") { str = "?"; for (var k in json) { if (str != "?") { str += "&"; } str += k + "=" + json[k]; } } return str; } private objectToFormData(obj: Object): FormData { const formData = new FormData(); for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; if (Array.isArray(value)) { for (const item of value) { formData.append(key, item); } } else { formData.append(key, value); } } } return formData; } private async quest(xhr: XMLHttpRequest, method: "GET" | "POST" | "PUT" = "GET", data: Object, formData: boolean = false) { return new Promise((resolve, reason) => { xhr.onreadystatechange = () => { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300) { // console.log("[Http] 返回", xhr.response); resolve(JSON.parse(xhr.response)); } else { reason(xhr.status) } } }; xhr.onerror = (error) => { console.error("http request onerror"); reason(error) }; xhr.ontimeout = (e) => { console.error("http request timeout"); reason(e) } //根据POST和GET方式,选择是否发送msg数据 if (formData) { xhr.send(this.objectToFormData(data)); } else { if (method == 'POST') { xhr.send(JSON.stringify(data)); } else if (method == 'PUT') { xhr.send(JSON.stringify(data)); } else { xhr.send(); } } }); } /**是否已登录成功 */ public static IsLogin(): boolean { return HttpUnit.LoginState == 2; } //登录 private loginCB: Function = null; public login(cb: Function = null) { this.loginCB = cb; SDKManager.login((_loginData) => { console.log("SDK登录成功", _loginData) SDKManager.getUserInfo((userInfo) => { console.log("SDK获取用户信息成功", userInfo) // let serparam = { // platform: _loginData.platform, // code: _loginData.code, // user_info: {nickName:userInfo.nickName, avatarUrl:userInfo.avatarUrl} // } if (GlobalValue.IsTest) { console.log("登录测试环境") this.loginSer({platform:0, code:12345}, this.initData.bind(this)) } else { if (_loginData.code == null) { let uuid = sys.localStorage.getItem('uuid'); if (!uuid) { uuid = Date.now(); //当前时间戳 sys.localStorage.setItem('uuid', uuid); } _loginData.code = uuid; } console.log("登录正式环境 loginData.code: ", _loginData.code) this.loginSer({platform:1, code:_loginData.code}, this.initData.bind(this)) } }) }) } private initData(playerData) { playerData = playerData || {}; this.loginCB && this.loginCB(playerData); } //登录服务器 private async loginSer(msg, cb: Function = null) { let data: any = await HttpUnit.ins.api("login", msg, "POST", true); console.log("login:", msg, data) if (data.code == 1) { HttpUnit.PlayerToken = data.data.token HttpUnit.LoginState = 2 console.log("HttpUnit.PlayerToken:", HttpUnit.PlayerToken) //获取玩家信息 // this.getUserInfo(cb); // this.getCommSetting(); HttpUnit.UserInfo = data.data.user_info; cb && cb(data.data.user_info); }else{ console.log("登陆失败:"+ data.msg); cb && cb(null); } } // //获取关卡数据 // public async getLevelStatus(cb: Function = null) { // let data: any = await HttpUnit.ins.api("game/status", {}, "POST", true); // console.log("关卡数据:", data) // if (data.code == 1) { // cb && cb(data.data); // }else{ // console.log("获取关卡数据失败:"+ data.msg); // cb && cb(null); // } // } /**开始关卡*/ public async levelStart(msg:any, cb: Function = null) { let data: any = await HttpUnit.ins.api("game/start", msg, "POST", true); console.log("开始关卡:", msg, data) if (data.code == 1) { cb && cb(data.data); }else{ console.log("开始关卡失败:"+ data.msg); cb && cb(null); } } public async api(path: string, data: any, method: "GET" | "POST" | "PUT" = "GET", bLock: boolean = false, isFormData: boolean = false) { let url = HttpUnit.ServerHttpHost + path; // console.log("[Http] 请求Url:",url, " 方式:", method, " Authorization:", GlobalValue.PlayerToken, " 数据:", JSON.stringify(data) ); bLock && this.lock(); var xhr = new XMLHttpRequest(); xhr.timeout = 10000; // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // if (cc.sys.isNative) { // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // } // xhr.setRequestHeader('authorization', Config.TOKEN); //发送数据 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"); } xhr.setRequestHeader('Authorization', "Bearer " + HttpUnit.PlayerToken); let self = this; return new Promise((resolve, reason) => { self.quest(xhr, method, data, isFormData).then(value => { bLock && self.unlock(); resolve(value); }).catch(err => { bLock && self.unlock(); resolve(null); }); }); } /** * 发送请求 * @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", bLock: boolean = false, formData: boolean = false) { // console.log("[Http] 请求Url:",url, " 方式:", method, " 数据:", data); bLock && this.lock(); 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, formData).then(value => { bLock && self.unlock(); resolve(value); }).catch(err => { bLock && self.unlock(); resolve(null); }); }); } /**解锁屏幕 */ private unlock() { // LockScreenUI.ins.unShowloading(); // Config.loading.hide2(); } /**锁屏 */ private lock() { // Config.loading.show2(); // LockScreenUI.ins.Showloading('网络加载中请稍后...'); } }