cocos http封装

1

export class HttpUtil{

 private static baseUrl:string = "https://xxx.xxx.xxx/xxxx/";

 public static get(url, params:object = {}, callback){
 let dataStr = ''; 
 Object.keys(params).forEach(key => {
 dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
        })
 if (dataStr !== '') {
 dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
 url = url + '?' + dataStr;
        }
 url = HttpUtil.baseUrl + url;
 let xhr = cc.loader.getXMLHttpRequest();
 xhr.open("GET", url, true);
 xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");  
 xhr.onreadystatechange = function () {
 if (xhr.readyState === 4) {
 let response = xhr.responseText;
 if (xhr.status >= 200 && xhr.status < 300) {
 let httpStatus = xhr.statusText;
 callback(true, JSON.parse(response));
                }else{
 callback(false, response);
                }
            }
        };
 xhr.send();
    }

 //Post请求
 public static post(url, param:object = {}, callback){
 url = HttpUtil.baseUrl + url;
 var xhr = cc.loader.getXMLHttpRequest();  
 let dataStr = ''; 
 Object.keys(param).forEach(key => {
 dataStr += key + '=' + encodeURIComponent(param[key])+ '&';
        })
 if (dataStr !== '') {
 dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        }
 xhr.open("POST", url, true);
 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"
        );  
 xhr.onreadystatechange = function () {  
 if (xhr.readyState === 4) {
 let response = xhr.responseText;
 if (xhr.status >= 200 && xhr.status < 300) {
 let httpStatus = xhr.statusText;
 callback(true, JSON.parse(response));
                }else{
 callback(false, response);
                }
            }
        };
 xhr.send(dataStr);
    }
}

2

const HttpHelper = cc.Class({
    extends: cc.Component,

    statics: {
    },

    properties: {

    },

    /**
     * get请求
     * @param {string} url 
     * @param {function} callback 
     */
    httpGet(url, callback) {
        //cc.myGame.gameUi.onShowLockScreen();
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.onreadystatechange = function () {
            // cc.log("Get: readyState:" + xhr.readyState + " status:" + xhr.status);
            if (xhr.readyState === 4 && xhr.status == 200) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                //cc.myGame.gameUi.onHideLockScreen();
                callback(rsp);
            } else if (xhr.readyState === 4 && xhr.status == 401) {
                //cc.myGame.gameUi.onHideLockScreen();
                callback({ status: 401 });
            } else {
                //callback(-1);
            }


        };
        xhr.withCredentials = true;
        xhr.open('GET', url, true);

        // if (cc.sys.isNative) {
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type,authorization');
        xhr.setRequestHeader("Content-Type", "application/json");
        // xhr.setRequestHeader('Authorization', 'Bearer ' + //cc.myGame.gameManager.getToken());
        // xhr.setRequestHeader('Authorization', 'Bearer ' + "");
        // }

        // note: In Internet Explorer, the timeout property may be set only after calling the open()
        // method and before calling the send() method.
        xhr.timeout = 8000;// 8 seconds for timeout

        xhr.send();
    },

    /**
     * post请求
     * @param {string} url 
     * @param {object} params 
     * @param {function} callback 
     */
    httpPost(url, params, callback) {
        //cc.myGame.gameUi.onShowLockScreen();
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.onreadystatechange = function () {
            // cc.log('xhr.readyState=' + xhr.readyState + '  xhr.status=' + xhr.status);
            if (xhr.readyState === 4 && xhr.status == 200) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                //cc.myGame.gameUi.onHideLockScreen();
                callback(rsp);
            } else {
                callback(-1);
            }
        };
        xhr.open('POST', url, true);
        // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        // if (cc.sys.isNative) {
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // xhr.setRequestHeader('Authorization', 'Bearer ' + //cc.myGame.gameManager.getToken());
        // }

        // note: In Internet Explorer, the timeout property may be set only after calling the open()
        // method and before calling the send() method.
        xhr.timeout = 8000;// 8 seconds for timeout
        // xhr.send(params);
        xhr.send(JSON.stringify(params));
    },

    /**
     * 登录专用
     * @param {string} url 
     * @param {object} params 
     * @param {function} callback 
     * @param {string} account 
     * @param {string} password 
     */
    httpPostLogin(url, params, callback, account, password) {
        //cc.myGame.gameUi.onShowLockScreen();
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.onreadystatechange = function () {
            // cc.log('xhr.readyState=' + xhr.readyState + '  xhr.status=' + xhr.status);
            if (xhr.readyState === 4 && xhr.status == 200) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                //cc.myGame.gameUi.onHideLockScreen();
                callback(rsp);
            } else {
                callback(-1);
            }
        };
        xhr.open('GET', url, true);
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
        xhr.setRequestHeader("Content-Type", "application/json");
        let str = account + "@" + password;
        xhr.setRequestHeader('Authorization', 'Basic' + ' ' + window.btoa(str));

        xhr.timeout = 8000;// 8 seconds for timeout

        xhr.send(JSON.stringify(params));

    },
    //获取状态专用
    httpPostStatue(url, params, callback, account, password) {
        //cc.myGame.gameUi.onShowLockScreen();
        let xhr = cc.loader.getXMLHttpRequest();
        let dataStr = '';
        Object.keys(params).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        }

        xhr.onreadystatechange = function () {
            // cc.log('xhr.readyState=' + xhr.readyState + '  xhr.status=' + xhr.status);
            if (xhr.readyState === 4 && xhr.status == 200) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                //cc.myGame.gameUi.onHideLockScreen();
                callback(rsp);
            } else {
                callback(-1);
            }
        };
        xhr.open('POST', url, true);
        // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        // xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
        // xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.timeout = 8000;// 8 seconds for timeout
        // xhr.send(params);
        xhr.send(dataStr);
    }
});

window.HttpHelper = new HttpHelper();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值