用2dx的lua 做安卓开发,使用 cc.XMLHttpRequest:new() 创建一个xhr对象 来做网络通信,代码如下:
function NetworkManager:sendHttpRequest(url,parameterTab,callback,method)
if method == nil then
–todo
method = “POST”;
end
local xhr = cc.XMLHttpRequest:new()
xhr:setRequestHeader("Content-Type","application/json; charset=utf-8");
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON-- cc.XMLHTTPREQUEST_RESPONSE_STRING-- cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER -- cc.XMLHTTPREQUEST_RESPONSE_JSON
local function onReadyStateChanged()
local isSuccess = false;
if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then -- 成功
isSuccess = true;
else
end
callback(xhr,isSuccess);
xhr:unregisterScriptHandler()
end
xhr:registerScriptHandler(onReadyStateChanged)
local parameterStr = "";
local dataJsonStr = nil;
if parameterTab ~= nil and table.nums(parameterTab) >0 then
--todo
local isFirstParameter = true;
dataJsonStr = CustomHelper.getJsonStrWithJsonTab(parameterTab);
for k,v in pairs(parameterTab) do
if isFirstParameter then
--todo
parameterStr = parameterStr..k.."="..v
isFirstParameter = false
else
parameterStr = parameterStr.."&"..k.."="..v
end
end
end
if method == "POST" then
--todo
xhr:open(method,url);
-- if parameterTab ~= nil and table.nums(parameterTab) > 0 then
-- --todo
-- end
xhr:send(dataJsonStr)
elseif method == "GET" then
--todo
url = url.."?"..parameterStr;
-- print("url:",url)
xhr:open(method,url);
xhr:send()
end
return xhr;
end
刚开始是安卓低版本sdk使用http可以通信,后来升级到高版本安卓sdk只能使用https。
自己搭建了一个网站 https://www.xsctest.store (有证书,浏览器也信任) ,作为参数 url 传递进去 但是通信一直失败。如果把 https://www.baidu.com/ 作为url参数传递就不会失败。
失败时候打印结果是
xhr.readyState: 1
xhr.status : 0
不知道为什么原因,有人能指点一下吗。