通过 lua 脚本访问 REST API

Access REST API via lua script

有没有办法用纯 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

在linux、mac中我们可以轻松安装luarocks,然后我们就可以安装curl包了。这是像 os.

这样的 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。然后 luarock install 命令无法正常工作,等等。

首先从官方网站下载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

如果您正确执行这些步骤,这将 1000% 成功