通过lua脚本访问REST API

有没有纯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
点赞
用户10295288
用户10295288

在 Linux 和 Mac OS 系统中,我们可以很容易地安装 luarocks,然后安装 curl 包。这是类 Unix 操作系统中最简单的方法。


-- 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 系统中我遇到了一些问题。不能正确地安装 luarocks,然后 luarocks 安装命令无法正常工作,等等……

首先我从官方网站下载了 Lua,然后按照下面网站的结构创建了目录:

http://fuchen.github.io/dev/2013/08/24/install-luarocks-on-windows/

然后我下载了 lua luadist http://luadist.org/

然后我得到了相同的结构 luadist 解压文件夹和 lua 文件夹。

合并 luadist 文件夹和 lua 文件夹,最后我们就能使用 http.soket

local 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

如果您正确完成这些步骤,这将百分之百地工作做到了。

2020-04-06 16:01:26