lua安装LuaSocket实现CURL的GET/POST请求

Song3991 次浏览0个评论2018年09月11日

安装luarocks

LuaRocksLua模块的包管理器。这里只介绍ubuntu/debian安装luarocks,其它系统类似

apt-get install luarocks

安装LuaSocket

安装LuaSocket有两种方法,源码安装和luarocks安装。这只介绍luarocks的安装方法,其他的可以查看源码安装luasocket

luarocks install luasocket

LuaSocket的使用

接下来介绍一下LuaSocket的基本使用

1、输出一个 LuaSocket 版本信息

local socket = require("socket")
print(socket._VERSION)

2、发送HTTP请求

我们来发送http请求

-- http访问请求
http=require("socket.http")
result=http.request("http://ip.taobao.com/service/getIpInfo.php?ip=123.189.1.100")
print(result)

如果要发送post请求

http.request{
  url = string,
  [sink = LTN12 sink,]
  [method = string,]
  [headers = header-table,]
  [source = LTN12 source],
  [step = LTN12 pump step,]
  [proxy = string,]
  [redirect = boolean,]
  [create = function]
}
  • methodHTTP请求方法。默认为GET;
  • headers:随请求一起发送的任何其他HTTP头;
  • source:”请求标头字段,否则该函数将尝试将主体发送为“ chunked ”(少数服务器支持的东西)。默认为空源;
  • stepLTN12步功能用于移动数据。默认为LTN12 pump.step功能。
  • proxy:要使用的代理服务器的URL。默认为无代理;
  • redirect:设置为false以防止该功能自动跟踪301302服务器重定向消息;
  • create:创建通信套接字时使用的可选函数,而不是socket.tcp

例子:

#!/usr/bin/env lua
local http=require("socket.http");
local ltn12 = require("ltn12");

local request_body = [[login=user&password=123]]
local response_body = {}

local res, code, response_headers = http.request{
    url = "http://httpbin.org/post",
    method = "POST",
    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

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文

    当前暂无更多相关好文推荐...