

测试了通过http对网站进行访问,拆解返回的json.
试了自己模拟Button,确实没有看到Defold有这个控件.
httpClient.lua单独文件保存,之后作为库引用
local http_client = {}
-- 发送GET请求
function http_client.get(url, headers, callback)
-- 确保headers是一个表
headers = headers or {}
-- 发送HTTP GET请求
http.request(url, "GET", function(self, id, response)
-- 处理响应
if response.status == 200 then
-- 请求成功
callback(true, response.response, response)
else
-- 请求失败
callback(false, "HTTP error: " .. response.status, response)
end
end, headers)
end
-- 发送POST请求
function http_client.post(url, data, headers, callback)
-- 确保headers是一个表
headers = headers or {}
-- 如果发送的是JSON数据,设置默认Content-Type
if not headers["Content-Type"] then
headers["Content-Type"] = "application/json"
-- 如果数据不是字符串,尝试序列化为JSON
if type(data) ~= "string" then
data = json.encode(data)
end
end
-- 发送HTTP POST请求
http.request(url, "POST", function(self, id, response)
-- 处理响应
if response.status == 200 or response.status == 201 then
-- 请求成功
callback(true, response.response, response)
else
-- 请求失败
callback(false, "HTTP error: " .. response.status, response)
end
end, headers, data)
end
-- 发送JSON数据的POST请求(简化版)
function http_client.post_json(url, json_data, callback)
local data = type(json_data) == "string" and json_data or json.encode(json_data)
local headers = {
["Content-Type"] = "application/json"
}
http_client.post(url, data, headers, callback)
end
-- 示例使用
function http_client.example()
-- 示例GET请求
http_client.get("https://api.example.com/data", nil, …
请微信扫码打赏,留言中输入文章编号. 附费后将自动刷新出完整内容.
打赏