cocos2dx 网络连接
2015-07-29 23:28
519 查看
XMLHttpRequest
---------------------------------------------- -- 数据转换,将请求数据 由table转化为string function dataParse(data) if type(data) ~= "table" then return nil end local tmp = {} for key, value in pairs(data) do table.insert(tmp, key .. "=" .. value) end local newData = "" for i = 1, #tmp do newData = newData .. tostring(tmp[i]) if i < #tmp then newData = newData .. "&" end end -- cclog("data:" .. newData) return newData end --------------------------------- -- POST 型,发送数据 function sendInfoToSync() local url = "www.baidu.com" -- 网址 local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr.timeout = 30 -- 判断连接超时时间,秒 -- 响应函数 local onReadyFunc = function() if xhr.status ~= -1 then -- 连接成功 local result = xhr.response -- string local cjson = require("cjson") local info = cjson.decode(result) -- json 解析成table else -- 连接失败 end end xhr:registerScriptHandler(onReadyFunc) xhr:open("POST",url) local data = {} data.account = 1 local newData = dataParse(data) xhr:send(newData) end -------------------------------------- -- GET型,获取数据 function loadInfoFromSync() local url = "www.baidu.com" local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON xhr.timeout = 30 local onReadyFunc = function() if xhr.status ~= -1 then -- 连接成功 local result = xhr.response -- string local cjson = require("cjson") local info = cjson.decode(result) -- json 解析成table else -- 连接失败 end end xhr:registerScriptHandler(onReadyFunc) local data = {} data.account = 1 local newData = url .. "?" .. dataParse(data) xhr:open("GET",newData) xhr:send() end
相关文章推荐
- OKHttp源码解析(二)
- Android核心基础-7.Android 网络通信-2.使用开源项目AsyncHttpClient
- HTTP协议
- socket连接和HTTP连接的区别
- WEB服务器、应用程序服务器、HTTP服务器有何区别
- $GLOBALS ["HTTP_RAW_POST_DATA"]为空
- pxe+kickstart 实现基于网络的无人值守安装操作系统
- Unix网络编程--卷一:套接字联网API 读书笔记
- C#编程:网络连接状态的定时检测
- fwrite() ,fread()(cp:http://www.cnblogs.com/witxjp/archive/2011/03/21/1990519.html)
- 大陆为Android Studio设置HTTP代理
- 备注ocp_ORACLE专题网络
- apache和php在网络中的位置
- Ajax中的XMLHttpRequest对象详解
- CC3200 HTTP Cli通过POST的方式把json数据提交给服务器出现的问题
- iOS开发实现文字/图片的社交网络分享功能
- HTTPS的3种实现方法
- linux初学(十五)之linux网络基础
- TCP协议中的三次握手和四次挥手(图解)
- POJ1459网络流模板题