是否可以通过纯lua脚本访问rest api
GET / POST都需要访问和显示响应
我已经尝试过
local api = nil
local function iniit()
if api == nil then
-- body
api = require("http://api.com")
.create()
.on_get(function ()
return {name = "Apple",
id = 12345}
end)
end
end
-- HTTP Get
local curl = require('curl')
curl.easy{
url = 'api.xyz.net?a=data',
httpheader = {
"X-Test-Header1: Header-Data1",
"X-Test-Header2: Header-Data2",
},
writefunction = io.stderr -- use io.stderr:write()
}
:perform()
:close()
在Windows中,我遇到了几个问题。无法正确安装羽绒被。然后luarock install命令无法正常运行,等等。首先从官方网站下载dwnload lua,然后创建如下结构(在网站下方)
http://fuchen.github.io/dev/2013/08/24/install-luarocks-on-windows/
然后我下载
lua luadisthttp://luadist.org/
然后我得到相同的结构luadist
提取的文件夹和lua文件夹。合并的luadist
文件夹和lua文件夹最后,我们可以使用http.soketlocal http=require("socket.http"); local request_body = [[login=user&password=123]] local response_body = {} local res, code, response_headers = http.request{ url = "api.xyz.net?a=data", method = "GET", headers = { ["Content-Type"] = "application/x-www-form-urlencoded"; ["Content-Length"] = #request_body; }, source = ltn12.source.string(request_body), sink = ltn12.sink.table(response_body), } print(res) print(code) if type(response_headers) == "table" then for k, v in pairs(response_headers) do print(k, v) end end print("Response body:") if type(response_body) == "table" then print(table.concat(response_body)) else print("Not a table:", type(response_body)) end
如果您正确执行了这些步骤,则可以确保1000%正常工作