最近搜索

封闭 http请求 get 和 post

浏览:551
管理员 2021-09-16 10:12
/**
 * Http 请求封装
 */
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.open('GET', url, true);
        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;
        // 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);
        // 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/json");
        //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('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/json");
        let str = account + "@" + password;
        xhr.setRequestHeader('Authorization', 'Basic' + ' ' + window.btoa(str));
 
        xhr.timeout = 8000;// 8 seconds for timeout
 
        xhr.send(JSON.stringify(params));
 
    }
});

window.HttpHelper = new HttpHelper();





使用方法

image.png

import HttpHelper from './HttpHelper'


 window.HttpHelper.httpGet("http://localhost/api/cocos/get?data=cocos-get",function(rsp){
            console.log(rsp);
        });

        window.HttpHelper.httpPost("http://localhost/api/cocos/post","cocos-post",function(rsp){
            //post  这里会输出3次 -1  不知道 啥情况
            if(rsp!=-1){
                console.log(rsp);
            }
        });



post 后台代码

@CrossOrigin
@ResponseBody
@RequestMapping("/api/cocos/post")
public JSONObject post(HttpServletRequest request)throws Exception {
    JSONObject result = new JSONObject();
     StringBuffer sb = new StringBuffer();
    InputStream is = request.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String s = "";
    while ((s = br.readLine()) != null) {
        sb.append(s);
    }
    String result1 = sb.toString();
    System.out.println(result1);
 
    result.put("msg","123456adbd我爱北京");
    result.put("user", userDao.findAll());
    return result;
}



联系站长

站长微信:xiaomao0055

站长QQ:14496453