cocos creator基礎-(二十七)httpclient Get POST


1: 掌握creator http client GET操作;
2: 掌握creator 客戶端上傳文件;
3: 掌握creator客戶端下載文件;


http GET POST
1: Http client: GET POST是http的兩種操作;
2: 獲取網頁數據我們一般使用http Get,GET 傳遞參數通過?開始每個參數之間使用&來隔開;
3: 上傳數據我們一般使用POST協議來上傳;
4: 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模式;

http get
1: 使用http get提交參數請求;

http post
1: 使用http.js里面的post上傳文件數據;

http download
1: http Get 下載文件,並保存到本地;
 
客戶端代碼
// 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;

 

服務器代碼

// echo_server.js nodejs 服務器代碼
var express = require("express");
var path = require("path");
var app = express();
var fs = require("fs");

//設置跨域訪問
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.use(express.static(path.join(process.cwd(), "www_root")));
app.listen(6080);

app.get("/get", function (request, respones) {
    console.log(request.query);
    respones.send("HelloWorld!!!!");
});

app.post("/upload", function (request, respones) {
    request.now_len = 0;
    
    var file_name = "./upload/" + request.query.name;    

    var fd = fs.openSync(file_name, "w");

    request.on("data", function(data) {
        request.now_len += data.length;
        fs.write(fd, data, 0, data.length);
    });

    request.on("end", function() {
        console.log("upload file " + request.query.name + " SUCCESS");
        fs.close(fd);

        respones.send("OK");
    });
});

app.get("/download", function(request, respones) {
    var file_name = "./upload/" + request.query.name;

    fs.readFile(file_name, function(err, data) {
        if (err) {
            respones.send("file_err !");
            return;
        }
        respones.send(data);
    });
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM