在使用Cocos2d-lua進行開發遊戲的時候,使用XMLHttpRequest的頻率還是蠻高的!下面通過下載指定url的內容保存到本地記錄一下XMLHttpRequest的使用!
local XHRTest = class("XHRTest")
function XHRTest:ctor()
self:testXHRDemo()
end
function XHRTest:testXHRDemo()
local url = "https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=https%3A%2F%2Ftimgsa.baidu.com%2Ftimg%3Fimage%26quality%3D80%26size%3Db9999_10000%26sec%3D1568269246425%26di%3Dd942c344a1ef974b5ab6221db78740c5%26imgtype%3D0%26src%3Dhttp%253A%252F%252Fn.sinaimg.cn%252Fsports%252F2_img%252Fupload%252Fcf0d0fdd%252F469%252Fw564h705%252F20180515%252F1hPV-hapkuvm0824918.jpg&thumburl=https%3A%2F%2Fss3.bdstatic.com%2F70cFv8Sh_Q1YnxGkpoWK1HF6hhy%2Fit%2Fu%3D3731168461%2C758750724%26fm%3D26%26gp%3D0.jpg"
local filePath = cc.FileUtils:getInstance():getWritablePath() .. "KD.png"
self:xhrDemo(url, filePath, handler(self, self.XHRDemoCallFunc))
end
function XHRTest:XHRDemoCallFunc(filePath)
print("XHRDemoCallFunc filePath->", filePath)
end
function XHRTest:XHRDemo(targetURL, filePath, callFunc)
local xhr = cc.XMLHttpRequest:new() -- 創建XMLHttpRequest對象
xhr.timeout = 5 -- 設置超時時間
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING -- 設置返回內容的類型
xhr:open("GET", targetURL) -- 設置向服務器發送請求的類型(通常爲"GET"或"POST")和請求的目標URL
local function httpCallback()
if xhr.readyState == 4 and xhr.status == 200 then -- 成功獲取到服務器返回的數據response
local response = xhr.response
local file = io.open(filePath, "wb") -- 以可寫模式打開filePath指定(全路徑)的文件
file:write(response) -- 將response數據寫入文件
file:close() -- 關閉文件
if callFunc then
callFunc(filePath) -- 執行回調函數
end
xhr:unregisterScriptHandler() -- 移除監聽
end
end
xhr:registerScriptHandler(httpCallback) -- 註冊監聽,服務器返回時觸發回調函數
xhr:send() -- 發送請求
end
return XHRTest
執行testXHRDemo,然後進入本地可寫路徑,就可以找到下載下來的"KD.png"圖片文件了:
ps:
1、responseType
- 在lua_xml_http_request.cpp中的定義:
enum class ResponseType
{
STRING, // 字符串
ARRAY_BUFFER, // 二進制
BLOB, // 二進制類型的大對象
DOCUMENT, // Document對象
JSON // json
};
- 在NetworkConstants.lua中的映射:
cc.XMLHTTPREQUEST_RESPONSE_STRING = 0
cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER = 1
cc.XMLHTTPREQUEST_RESPONSE_BLOB = 2
cc.XMLHTTPREQUEST_RESPONSE_DOCUMENT = 3
cc.XMLHTTPREQUEST_RESPONSE_JSON = 4
2、readyState
在lua_xml_http_request.cpp中的定義:
static const unsigned short UNSENT = 0; // 初始化狀態。XMLHttpRequest 對象已創建或已被 abort() 方法重置。
static const unsigned short OPENED = 1; // open() 方法已調用,但是 send() 方法未調用。請求還沒有被髮送。
static const unsigned short HEADERS_RECEIVED = 2; // Send() 方法已調用,HTTP 請求已發送到 Web 服務器。未接收到響應。
static const unsigned short LOADING = 3; // 所有響應頭部都已經接收到。響應體開始接收但未完成。
static const unsigned short DONE = 4; // 響應已經完全接收。