27.httpclient Get POST

1. http GET POST

Http client: GET POST是http的两种操作;
获取网页数据我们一般使用http Get,GET 传递参数通过?开始每个参数之间使用&来隔开;
上传数据我们一般使用POST协议来上传;
download下载一般也用GET来做, xhr.responseType 指的是数据的类型:
     “” (默认)DOMString 是一个UTF-16字符串, DOMString 直接映射到 一个String
      "arraybuffer" 对象被用来表示一个通用的,固定长度的二进制数据缓冲区
     "blob" Blob对象表示不可变的类似文件对象的原始数据
     "json" JavaScript object, parsed from a JSON string returned by the server
     “text” DOMString
根据你要获取的数据类型来决定,比如下载一个文件,可以采用arraybuffer模式;

 

2. http get 提交参数请求

 

3. http post 使用http.js里面的post上传文件数据

 

4. http download 下载文件,并保存到本地

 

例子

game_scene.js

var http = require("http");

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {

    },

    on_get_click: function() {
        // 浏览器 http://127.0.0.1:6080/get?uname=blake&phone=123456789
        http.get("http://127.0.0.1:6080", "/get", "uname=blake&phone=123456789", function(err, ret) {
            if(err) {
                console.log(err);
                return;
            }

            console.log(ret);
        });
    },

    // 文件上传
    on_upload_click: function() {
        // 测试只能在native平台
        
        var path = jsb.fileUtils.getWritablePath();
        var fileData = jsb.fileUtils.getDataFromFile(path + "logo.jpg");

        
        http.post("http://127.0.0.1:6080", "/upload", "name=upload.jpg", fileData, function(err, ret) {
            if(err) {
                console.log(err);
                return;
            }

            console.log(ret);
        });
    },

    on_download_bin_click: function() {
        http.download("http://127.0.0.1:6080", "/download.jpg", null, function(err, data) {
            var path = jsb.fileUtils.getWritablePath() + "/download.jpg";
            jsb.fileUtils.writeDataToFile(data, path);
        });
    },
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});

 http.js

var http = {
    // calback(err, data)
    // url 站点: http://www.baidu.com
    // path 子路径 /index.htm
    // params: key1=value1&key2=value2&key3=value3
    // callback: 当这个请求有回应的时候调用这个callback函数;
    // (err, ret) 如果有错误err != null, 如果没有错误error == null
    get: function(url, path, params, callback) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if (params) {
            requestURL = requestURL + "?" + params;
        }
         
        xhr.open("GET",requestURL, true);
        if (cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding","gzip,deflate","text/html;charset=UTF-8");
        }

        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
                console.log("http res("+ xhr.responseText.length + "):" + xhr.responseText);
                try {
                    // var ret = JSON.parse(xhr.responseText);
                    var ret = xhr.responseText;
                    if(callback !== null){
                        callback(null, ret);
                    }                        /* code */
                } catch (e) {
                    console.log("err:" + e);
                    callback(e, null);
                }
                finally{
                    if(cc.vv && cc.vv.wc){
                    //       cc.vv.wc.hide();    
                    }
                }
            }
        };
        
        if(cc.vv && cc.vv.wc){
            //cc.vv.wc.show();
        }
        xhr.send();
        return xhr;
    },

    // post和get区别是post能带数据body,其他的和get一样
    post: function(url, path, params, body, callback) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if (params) {
            requestURL = requestURL + "?" + params;
        }
        xhr.open("POST",requestURL, true);
        if (cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding","gzip,deflate","text/html;charset=UTF-8");
        }

        if (body) {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            // xhr.setRequestHeader("Content-Length", body.length);
        }
        

        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
                console.log("http res("+ xhr.responseText.length + "):" + xhr.responseText);
                try {
                    // var ret = JSON.parse(xhr.responseText);
                    var ret = xhr.responseText;
                    if(callback !== null){
                        callback(null, ret);
                    }                        /* code */
                } catch (e) {
                    console.log("err:" + e);
                    callback(e, null);
                }
                finally{
                    if(cc.vv && cc.vv.wc){
                    //       cc.vv.wc.hide();    
                    }
                }
            }
        };
        
        if(cc.vv && cc.vv.wc){
            //cc.vv.wc.show();
        }
        if (body) {
            xhr.send(body);
        }
        return xhr;
    }, 

    // 下载他是基于get操作,参数也一样,为什么不用get那个函数呢?
    download: function(url, path, params, callback) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if (params) {
            requestURL = requestURL + "?" + params;
        }

        xhr.responseType = "arraybuffer";  // 指定我们的数据类型

        xhr.open("GET",requestURL, true);
        if (cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding","gzip,deflate","text/html;charset=UTF-8");
        }

        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
                var buffer = xhr.response;
                var data = new Uint8Array(buffer); // arraybuffer, new Unit8Array
                callback(null, data);
            }
        };
        
        if(cc.vv && cc.vv.wc){
            //cc.vv.wc.show();
        }
        xhr.send();
        return xhr;
    },

    
};

module.exports = http;


 

 

 

你可能感兴趣的:(cocos,creator)