quick-cocos2d-x教程11:实现http通信,并与站点php对接,可实现登录等常见功能

手机游戏眼下是弱联网居多,http登录是经常使用功能。我们如今就来实现。

  • 在启动时候。自己主动请求http.
  • function MainScene:ctor()
        local url = "http://localhost/request.php"
        local request = network.createHTTPRequest(onRequestFinished, url, "POST")
        request:addPOSTValue("KEY", "VALUE")
        -- 開始请求。当请求完毕时会调用 callback() 函数
        request:start()
    end

  • ---注意onRequestFinished前面,不要加MainScence
    function onRequestFinished(event)
        local ok = (event.name == "completed")
        local request = event.request
     
        if not ok then
            -- 请求失败,显示错误代码和错误消息
            print(request:getErrorCode(), request:getErrorMessage())
            return
        end
     
        local code = request:getResponseStatusCode()
        if code ~= 200 then
            -- 请求结束,但没有返回 200 响应代码
            print(code)
            return
        end
     
        -- 请求成功。显示服务端返回的内容
        local response = request:getResponseString()
        print(response)
    end
  • request.php实现代码:
    <?

    php
    $tmpName=$_POST['KEY'];
    echo $tmpName."ok";
    ?>

  • 正常联网输出:
    VALUEok
  • 然后我们在手机应用上能够加输入账号password功能( request:addPOSTValue("KEY", "VALUE"),就相应名字和数值),然后在php中。增加相应的查询数据库功能,返回不同的结果。