Lua http工具类+Nginx

良心推荐

说明:此工具类需要安装Nginx,无法直接在luci上使用

lua发送http请求

https://zixuephp.net/article-448.html

lua发送http请求,luajit默认没有http.lua库,需要下载并存放到luajit对应目录。
一、下载http.lua和http_headers.lua库
下载页面:https://github.com/pintsized/lua-resty-http
直接下载:http_headers.lua-http.lua.rar

在这里插入图片描述
二、lua发送http请求代码
1.get请求

local zhttp = require "resty.http"
local function http_post_client(url, timeout)
        local httpc = zhttp.new()
 
        timeout = timeout or 30000
        httpc:set_timeout(timeout)
 
        local res, err_ = httpc:request_uri(url, {
                method = "GET",
                headers = {
                    ["Content-Type"] = "application/x-www-form-urlencoded",
                }
        })
        httpc:set_keepalive(5000, 100)
        --httpc:close()
        return res, err_
end

2.post请求

local zhttp = require "resty.http"
local function http_post_client(url,body,timeout)
        local httpc = zhttp.new()
 
        timeout = timeout or 30000
        httpc:set_timeout(timeout)
 
        local res, err_ = httpc:request_uri(url, {
                method = "POST",
                body = body,
                headers = {
                    ["Content-Type"] = "application/x-www-form-urlencoded",
                }
        })
        httpc:set_keepalive(5000, 100)
         httpc:close()
        if not res then 
            return nil, err_ 
         else if res.status == 200 then 
             return res.body, err_ 
         else 
             return nil, err_ end 
         end
 
end

3.示例

--get
local resp, err = http_post_client("http://zixuephp.net/index.html?name=test",3000)
--post
local body = {"name" = "test"}
local resp, err = http_post_client("http://zixuephp.net/index.html?name=test",body,3000)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值