lua中的http与https请求

时间:2022-11-09 14:24:25

OpenResty默认没有提供Http客户端,需要使用第三方提供;
此链接下载需要的资源:https://github.com/pintsized/lua-resty-http
http.lua http_headers.lua
这两个文件拷贝到openresty安装的lua的lib库。

local zhttp         = require("resty.http")

http

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",
}
})
if not res then
return nil, err_
else
if res.status == 200 then
return res.body, err_
else
return nil, err_
end
end
end

https

function https_post_client(url, body, timeout, ssl_verify)
local httpc = zhttp.new()

timeout = timeout or 30000
httpc:set_timeout(timeout)
--ssl_verify
--传参表示:用于客户端时要求服务器必须提供证书,用于服务器时服务器会发出证书请求消息要求客户端提供证书
--不传参(false)表示:表示不验证
local res, err_ = httpc:request_uri(url, {
ssl_verify = ssl_verify or false,
method = "POST",
body = body,
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
}
})

if not res then
return nil, err_
else
if res.status == 200 then
return res.body, err_
else
return nil, err_
end
end

end