欢迎喜欢或者从事CocosCreator开发的小伙伴请加入我的大家庭CocosCreator游戏开发Q群:26855530
import SysLog from "./SysLog";
import PublicUtil from "./PublicUtil";
import ServerConfig from "../common/ServerConfig";
import UserData from "../data/UserData";
class HttpUtil {
private static instance: HttpUtil;
private constructor() {
}
static getInstance(): HttpUtil {
if (!HttpUtil.instance) {
HttpUtil.instance = new HttpUtil();
}
return this.instance;
}
httpGets(url, callback, errorCallback?) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
let responseText = PublicUtil.unCode(xhr.responseText);//解密
//let responseText = xhr.responseText;//SysLog("josn:"+responseText);
if (xhr.status == 200) {
if (responseText) {
SysLog.debug("responseText:" + responseText);
let jsonObj = JSON.parse(responseText);
let detail = jsonObj["detail"];
if (detail) {
callback(detail);
}
}
} else {
SysLog.debug("连接服务器失败....");
}
}
};
xhr.onerror = function () {
if (typeof errorCallback == 'function') {
errorCallback();
}
};
xhr.open("GET", url, true);
if (cc.sys.isNative) {
xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
}
// note: In Internet Explorer, the timeout property may be set only after calling the open()
// method and before calling the send() method.
xhr.timeout = 5000;// 5 seconds for timeout
xhr.send();
}
gameHttpPost(url: string, params: string | any, callback, errorCallback?) {
//追加session验证
if (typeof params === 'string') {
let sess = UserData.Map_UserInfo_ALL.get("sess");
params = params.replace("}", ',"tokenId":"' + sess + '"}');
}
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
let responseText = PublicUtil.unCode(xhr.responseText);//解密
//let responseText = xhr.responseText;//SysLog("josn:"+responseText);
if (xhr.status == 200) {
if (responseText) {
//SysLog.debug("responseText:" + responseText);
let jsonObj = JSON.parse(responseText);
let detail = jsonObj["detail"];
if (detail) {
callback(detail);
}
}
} else {
if (typeof errorCallback == 'function') {
errorCallback();
}
}
}
};
xhr.onerror = function () {
if (typeof errorCallback == 'function') {
errorCallback();
}
};
xhr.open("POST", ServerConfig.game_mainPoint + url);
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xhr.timeout = 5000;// 5 seconds for timeout
xhr.send(PublicUtil.enCode(params));//加密
//xhr.send(params);
}
}
export default HttpUtil;
使用方式:(简单的单例模式调用)
HttpUtil.getInstance().gameHttpPost('地址', JSON.stringify(jsonObj), (datas:any) => {
//后端返回的datas
});