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

前端之家收集整理的这篇文章主要介绍了cocos2d-x lua 使用http(下载图片, POST JSON)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

version: cocos2d-x 3.6

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

  1. require("src/cocos/cocos2d/json")
  2. require("src/cocos/network/NetworkConstants")
  3.  
  4. -- post json
  5. local xhr = cc.XMLHttpRequest:new()
  6. xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
  7. xhr:setRequestHeader("Content-Type","application/json")
  8. xhr:open("POST","www.baidu.com")
  9. local function loginCallback()
  10. print("xhr.readyState is:",xhr.readyState,"xhr.status is: ",xhr.status)
  11. if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
  12. local response = xhr.response
  13. local output = json.decode(response)
  14. -- print
  15. table.foreach(output,function(i,v) print (i,v) end)
  16.  
  17. -- success ...
  18. else
  19. -- fail ...
  20. end
  21. end
  22. xhr:registerScriptHandler(loginCallback)
  23. xhr:send(sendJson)@H_403_86@

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

  25. -- get (image)
  26. pSprite:retain()  -- a sprite
  27. local xhr = cc.XMLHttpRequest:new()
  28. -- tag
  29. xhr._urlFileName = urlFileName
  30. xhr._urlSprite = pSprite
  31. xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
  32. xhr:open("GET","http://cocos2d-x.org/s/images/img-cocos2dx.jpg")
  33. local function onDownloadImage()
  34.     print("xhr.readyState is:",xhr.status)
  35.     if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
  36.         local fileData = xhr.response
  37.         local fullFileName = cc.FileUtils:getInstance():getWritablePath() .. "/" .. xhr._urlFileName
  38.         local file = io.open(fullFileName,"wb")
  39.         file:write(fileData)
  40.         file:close()
  41.         local texture2d = cc.Director:getInstance():getTextureCache():addImage(fullFileName)
  42.         local pSprite = xhr._urlSprite
  43.         if texture2d then
  44.             pSprite:setTexture(texture2d)
  45.         end
  46.         pSprite:release() -- be careful
  47.     end
  48. end
  49. xhr:registerScriptHandler(onDownloadImage)
  50. xhr:send()@H_403_86@ 
  51.  
    • 在使用xhr时,可以添加自己的数据(如:xhr._urlSprite = pSprite),存放用户的临时数据,方便返回时使用。

猜你在找的Cocos2d-x相关文章