Cocos2d-x   发布时间:2022-05-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了cocos2d-x lua 使用http(下载图片, POST JSON)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

cocos2d-x lua 使用http(下载图片,POST JSON)

version: cocos2d-x 3.6

1.使用http post json与服务器交互

require("src/cocos/cocos2d/json")
require("src/cocos/network/NetworkConstants")

-- post json
local xhr = cc.XMLhttprequest:new()
xhr.responsetype = cc.XMLhttprequEST_RESPONSE_JSON
xhr:setrequestHeader("Content-Type","application/json")
xhr:open("POST","www.baidu.com")
local function loginCallBACk()
    print("xhr.readyState is:",xhr.readyState,"xhr.status is: ",xhr.status)
    if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
        local response = xhr.response
        local output = json.decode(responsE)
        -- print
        table.foreach(output,function(i,v) print (i,v) end)

        -- success ...
    else
        -- fail ...
    end
end
xhr:registerScriptHandler(loginCallBACk)
xhr:send(sendJson)

2.使用http get下载网络图片

-- get (imagE)

pSprite:retain()  -- a sprite
local xhr = cc.XMLhttprequest:new()

-- tag
xhr._urlFilename = urlFilename
xhr._urlSprite = pSprite

xhr.responsetype = cc.XMLhttprequEST_RESPONSE_StriNG
xhr:open("GET","http://cocos2d-x.org/s/images/img-cocos2dx.jpg")
local function onDownloadImage()
    print("xhr.readyState is:",xhr.status)
    if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
        local fileData = xhr.response
        local fullFilename = cc.FileUtils:geTinstance():getWritablePath() .. "/" .. xhr._urlFilename
        local file = io.open(fullFilename,"wb")
        file:write(fileData)
        file:close()
        local texture2d = cc.Director:geTinstance():getTextureCache():addImage(fullFileName)
        local pSprite = xhr._urlSprite
        if texture2d then
            pSprite:setTexture(texture2d)
        end
        pSprite:release() -- be careful
    end
end
xhr:registerScriptHandler(onDownloadImagE)
xhr:send()
    @H_801_197@在使用Xhr时,可以添加自己的数据(如:xhr._urlSprite = pSprite),存放用户的临时数据,方便返回时使用。

大佬总结

以上是大佬教程为你收集整理的cocos2d-x lua 使用http(下载图片, POST JSON)全部内容,希望文章能够帮你解决cocos2d-x lua 使用http(下载图片, POST JSON)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。