CCHttpRequest的用法很簡單
1、Get方法,設置URL,響應事件:
[html]
--[[
設置ulr:"http://blog.csdn.net/longolder"
監聽:self:onResponseGet(event)
方法:GET
--]]
local url = "http://blog.csdn.net/longolder"
local request = network.createHTTPRequest(function(event)
self:onResponseGet(event)
end, url, "GET")
request:setTimeout(30)
request:start()
--[[ 設置ulr:"http://blog.csdn.net/longolder" 監聽:self:onResponseGet(event) 方法:GET --]] local url = "http://blog.csdn.net/longolder" local request = network.createHTTPRequest(function(event) self:onResponseGet(event) end, url, "GET") request:setTimeout(30) request:start()
默認超時時間為10s,這裡調用setTimeout設置30s超時
2、POST方法,與GET方法相似,只不過要另外添加數據:
[html]
-- 調用addPOSTValue向Form中添加鍵值對例如:key:value
for key, value in pairs(dataInfo) do
request:addPOSTValue(key, value)
end
-- 調用addPOSTValue向Form中添加鍵值對例如:key:value for key, value in pairs(dataInfo) do request:addPOSTValue(key, value) end
dataInfo是一個保存要發送數據的table集合
下面是回調方法:
[html]
function HttpRequestTest:onResponseGet(event)
local request = event.request
if event.name ~= "completed" then -- 當為completed表示正常結束此事件
print("request:getErrorCode(), request:getErrorMessage() ", request:getErrorCode(), request:getErrorMessage())
return
end
local code = request:getResponseStatusCode()
if code ~= 200 then -- 成功
print("code ", code)
return
end
local strResponse = string.trim(request:getResponseString())
print(strResponse)
end
function HttpRequestTest:onResponseGet(event) local request = event.request if event.name ~= "completed" then -- 當為completed表示正常結束此事件 print("request:getErrorCode(), request:getErrorMessage() ", request:getErrorCode(), request:getErrorMessage()) return end local code = request:getResponseStatusCode() if code ~= 200 then -- 成功 print("code ", code) return end local strResponse = string.trim(request:getResponseString()) print(strResponse)end
常用的狀態碼有以下幾個值:
200 - 服務器成功返回網頁
404 - 請求的網頁不存在
503 - 服務器暫時不可用