Cocos2d-x 3.2 Lua示例 XMLHttpRequestTest(Http网络请求)

From: http://blog.csdn.net/wwj_748/article/details/38491393

本篇博客介绍Cocos2d-x 3.2Lua示例中的XMLHttpRequestTest,这里提供GET和POST两种http请求方式,返回数据类型有以下几种:
cc.XMLHTTPREQUEST_RESPONSE_STRING = 0  -- 返回字符串类型
cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER = 1 -- 返回字节数组类型
cc.XMLHTTPREQUEST_RESPONSE_BLOB   = 2 -- 返回二进制大对象类型
cc.XMLHTTPREQUEST_RESPONSE_DOCUMENT = 3 -- 返回文档对象类型
cc.XMLHTTPREQUEST_RESPONSE_JSON = 4 -- 返回JSON数据类型


这些常量的定义可以到Cocos2dConstants.lua下找到。

示例代码:XMLHttpRequestTest.lua

--[[
=================
XMLHttpRequestTest.lua
http请求
=================
]]--
require("json")

local function XMLHttpRequestLayer()
  local layer = cc.Layer:create()-- 创建层
  local winSize = cc.Director:getInstance():getWinSize()-- 得到窗口大小
  local margin = 40-- 间距
  local space  = 35-- 宽度
  local s_arialPath = "fonts/arial.ttf"
  local s_markerFeltFontPath = "fonts/Marker Felt.ttf"

  local function init()
    local label = cc.Label:createWithTTF("XML Http Request Test", s_arialPath, 28)-- 使用ttf文字格式的标签
    label:setAnchorPoint(cc.p(0.5, 0.5))-- 设置锚点
    label:setPosition(cc.p(winSize.width / 2, winSize.height - margin))-- 设置显示位置,宽度为屏幕的中间,高度为屏幕高度减去间距
    layer:addChild(label, 0) -- 添加标签到层中

    -- 显示返回码的标签
    local labelStatusCode = cc.Label:createWithTTF("HTTP Status Code", s_markerFeltFontPath, 20)
    labelStatusCode:setAnchorPoint(cc.p(0.5, 0.5))
    labelStatusCode:setPosition(cc.p(winSize.width / 2,  winSize.height - margin - 6 * space))
    layer:addChild(labelStatusCode)

    local menuRequest = cc.Menu:create() -- 创建菜单
    menuRequest:setPosition(cc.p(0,0))
    layer:addChild(menuRequest) -- 添加菜单

    --Get
    local function onMenuGetClicked()
      local xhr = cc.XMLHttpRequest:new() -- http请求
      xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING -- 响应类型
      xhr:open("GET", "http://httpbin.org/get") -- 打开链接

      -- 状态改变时调用
      local function onReadyStateChange()
        -- 显示状态文本
        local statusString = "Http Status Code:"..xhr.statusText
        labelStatusCode:setString(statusString)
        print(xhr.response)
      end

      -- 注册脚本回调方法
      xhr:registerScriptHandler(onReadyStateChange)
      xhr:send() -- 发送请求

      labelStatusCode:setString("waiting...")
    end

    -- 测试Get的标签
    local labelGet  = cc.Label:createWithTTF("Test Get", s_arialPath, 22)
    labelGet:setAnchorPoint(cc.p(0.5, 0.5))
    local itemGet  =  cc.MenuItemLabel:create(labelGet) -- 菜单标签
    itemGet:registerScriptTapHandler(onMenuGetClicked) -- 菜单点击事件
    itemGet:setPosition(cc.p(winSize.width / 2, winSize.height - margin - space))
    menuRequest:addChild(itemGet) -- 添加菜单项

    --Post
    local function onMenuPostClicked()
      local xhr = cc.XMLHttpRequest:new() -- 新建一个XMLHttpRequest对象
      xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING -- 相应类型为字符串
      xhr:open("POST", "http://httpbin.org/post")-- post方式
      local function onReadyStateChange()
        labelStatusCode:setString("Http Status Code:"..xhr.statusText)
        print(xhr.response)
      end
      -- 注册脚本方法回调
      xhr:registerScriptHandler(onReadyStateChange)
      xhr:send()-- 发送

      labelStatusCode:setString("waiting...")
    end

    -- 测试Post的标签
    local labelPost = cc.Label:createWithTTF("Test Post", s_arialPath, 22)
    labelPost:setAnchorPoint(cc.p(0.5, 0.5)) -- 设置锚点
    local itemPost =  cc.MenuItemLabel:create(labelPost) -- 设置菜单项标签
    itemPost:registerScriptTapHandler(onMenuPostClicked) -- 注册菜单项点击回调方法
    itemPost:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 2 * space))
    menuRequest:addChild(itemPost)

    --Post Binary
    local function onMenuPostBinaryClicked()
      local xhr = cc.XMLHttpRequest:new()-- 新建一个XMLHttpRequest对象
      xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER --返回数据为字节流
      xhr:open("POST", "http://httpbin.org/post") -- 打开Socket

      -- 状态改变时调用
      local function onReadyStateChange()
        local response   = xhr.response -- 获得返回数据
        local size     = table.getn(response) -- 获得返回数据大小
        local strInfo = ""

        for i = 1,size do
          if 0 == response[i] then
            strInfo = strInfo.."\'\\0\'"
          else
            strInfo = strInfo..string.char(response[i])
          end
        end
        labelStatusCode:setString("Http Status Code:"..xhr.statusText)
        print(strInfo)
      end

      -- 注册脚本方法回调
      xhr:registerScriptHandler(onReadyStateChange)
      xhr:send()-- 发送

      labelStatusCode:setString("waiting...")
    end

    -- 测试使用Post请求方式发送字节流
    local labelPostBinary = cc.Label:createWithTTF("Test Post Binary", s_arialPath, 22)
    labelPostBinary:setAnchorPoint(cc.p(0.5, 0.5))
    local itemPostBinary = cc.MenuItemLabel:create(labelPostBinary)
    itemPostBinary:registerScriptTapHandler(onMenuPostBinaryClicked)
    itemPostBinary:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 3 * space))
    menuRequest:addChild(itemPostBinary)

    --Post Json
    local function onMenuPostJsonClicked()
      local xhr = cc.XMLHttpRequest:new() -- 新建一个XMLHttpRequest对象
      xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON -- json数据类型
      xhr:open("POST", "http://httpbin.org/post")-- POST方式

      local function onReadyStateChange()
        -- 显示状态码,成功显示200
        labelStatusCode:setString("Http Status Code:"..xhr.statusText)
        local response   = xhr.response -- 获得响应数据
        local output = json.decode(response,1) -- 解析json数据
        table.foreach(output,function(i, v) print (i, v) end)
        print("headers are")
        table.foreach(output.headers,print)
      end

      -- 注册脚本方法回调
      xhr:registerScriptHandler(onReadyStateChange)
      xhr:send()-- 发送请求

      labelStatusCode:setString("waiting...")
    end

    -- 测试使用POST方式发送json的标签
    local labelPostJson = cc.Label:createWithTTF("Test Post Json", s_arialPath, 22)
    labelPostJson:setAnchorPoint(cc.p(0.5, 0.5)) -- 锚点
    local itemPostJson = cc.MenuItemLabel:create(labelPostJson) -- 菜单项标签
    itemPostJson:registerScriptTapHandler(onMenuPostJsonClicked) -- 注册菜单项点击
    itemPostJson:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 4 * space))
    menuRequest:addChild(itemPostJson)
  end


  -- 节点回调事件
  local function onNodeEvent(eventName)
    if "enter" == eventName then
      init()
    end
  end
  
  -- 注册层的监听回调事件
  layer:registerScriptHandler(onNodeEvent)

  return layer
end

function XMLHttpRequestTestMain()
  local scene = cc.Scene:create() -- 创建场景
  scene:addChild(XMLHttpRequestLayer()) -- 添加层
  --scene:addChild(CreateBackMenuItem()) -- 添加返回菜单项,具体实现查看helper.lua文件
  return scene
end


效果图如下:

Test Get:


Test Post:


Test Post Binary:



Test Post JSON:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值