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); }); });