对cocos2dx lua中http请求的简要封装和使用

31 篇文章 0 订阅
26 篇文章 2 订阅

使用

    ----------------------- 创建自定义事件 start
    local function eventCustomListener1(event)
        local str = "response: "..event._usedata
        labelStatusCode:setString(str)
        
          -- 如果返回的是 json 数据,这里解析        
--        local data =  json.decode(event._usedata)
--        table.foreach(data,
--            function(key, var)
--                print("-----"..key)
--                table.foreach(var,
--                    function(a, b)
--                        print(a.."-"..b)
--                    end)
--            end)
        
    end  
    
    local listener1 = cc.EventListenerCustom:create("customEvent1",eventCustomListener1)
    cc.Director:getInstance():setNotificationNode(cc.Node:create())
    local eventDispatcher = cc.Director:getInstance():getNotificationNode():getEventDispatcher()
    eventDispatcher:addEventListenerWithFixedPriority(listener1, 6)

    -- 将事件分配器赋值到HttpSingleton.eventDispatcher
    -- 用来在http请求返回的回调函数中使用,因为回调函数是在异步线程中执行,必须用自定义事件更新ui线程数据
    local tmpHttp = HttpSingleton:getInstance()
    tmpHttp.eventDispatcher = eventDispatcher
    ----------------------- 创建自定义事件 end

    local function testSingletonPost(sender)
    
        local tmp = HttpSingleton:getInstance()
        
        local function callback(xhr)
            local event = cc.EventCustom:new("customEvent1")
            event._usedata = xhr.response
            eventDispatcher:dispatchEvent(event)
            print("post callback code = "..xhr.statusText)
        end
        
        local type = tmp.POST
        local url = "http://localhost:8080/b_springmvc/luaTestPost.do"
        local dataPost = {}
        dataPost.data = "hello"
        dataPost.aaa = "world"
        dataPost.bbb = "yang"
        tmp:send(type, url, dataPost, callback)

    end

    local menu4 = createMenu("singletonPost",150,50,testSingletonPost)
    layer:addChild(menu4)

封装http请求代码

require "json"

HttpSingleton = {}
HttpSingleton.__index = HttpSingleton
HttpSingleton.instance = nil
HttpSingleton.callback = nil
HttpSingleton.POST = "POST"
HttpSingleton.GET = "GET"

function HttpSingleton:new()
    local self = {}
    setmetatable(self,HttpSingleton)
    return self
end

function HttpSingleton:getInstance()
    if nil == self.instance then
        self.instance = self:new()
    end
    return self.instance
end

-- 数据转换,将请求数据由 table 型转换成 string,参数:table
function HttpSingleton:dataParse(data)
    if "table" ~= type(data) then
        print("data is not a table")
        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
    print("------- name is "..newData)
    return newData
end

-- 发送数据,参数:string,string,table
function HttpSingleton:send(type, url, data, callback)
    local xhr = cc.XMLHttpRequest:new() --new 一个http request 实例
    self.callback = callback    --设置需要执行的函数
    
   local newData = self:dataParse(data)
   if nil == newData or "" == newData then
   	return 
   end
    
    -- response回调函数
    local function responseCallback()
        print("httpSingleton - "..xhr.response)
        if nil ~= self.callback then
            self.callback(xhr)
        else
            print("callback is nil")
        end
    end

    -- 设置返回值类型及回调函数
     xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
     xhr:registerScriptHandler(responseCallback)
         
    -- 请求方式判断
    if self.POST == type then
        xhr:open(self.POST, url)
        xhr:registerScriptHandler(responseCallback)
        xhr:send(newData)
    elseif self.GET == type then
        xhr:open(self.GET, url.."?"..newData)
        xhr:send()
    else
        print("ERROR : type only can be \"Post\" or \"GET\"")
    end
end


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝶泳奈何桥.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值