-- 加载 lua-resty-http 库
local http = require "resty.http"
local httpc = http.new()
-- 设置目标 URL
local url = "https://xiexianbin.cn"
-- 解析主机名和端口
local host = "xiexianbin.cn"
local port = 443
-- 建立 TCP 连接
local ok, err = httpc:connect({
scheme = "https",
host = host,
port = port,
ssl_verify = false -- 禁用 SSL 验证(仅用于测试,生产环境应启用)
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
-- 发送 HTTP 请求
local res, err = httpc:request({
path = "/",
headers = {
["Host"] = host,
["User-Agent"] = "lua-resty-http"
}
})
if not res then
ngx.say("failed to request: ", err)
return
end
-- 读取响应体
local body, err = res:read_body()
if not body then
ngx.say("failed to read body: ", err)
return
end
-- 关闭连接
local ok, err = httpc:close()
if not ok then
ngx.say("failed to close: ", err)
return
end
-- 输出响应状态码和内容
ngx.say("Status: ", res.status)
ngx.say("Body length: ", #body)
-- ngx.say("Body content: ", body) -- 如果需要输出完整内容可以取消注释
resty-http-post-demo...
text
local http = require "resty.http"
local httpc = http.new()
-- 目标 URL
local url = "https://xiexianbin.cn/api"
local host = "xiexianbin.cn"
local port = 443
-- 建立 HTTPS 连接(禁用 SSL 验证,仅测试用)
local ok, err = httpc:connect({
scheme = "https",
host = host,
port = port,
ssl_verify = false
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
-- 构造 POST 请求数据(JSON 格式)
local post_data = {
name = "John",
age = 30
}
local json_body = require("cjson").encode(post_data)
-- 发送 POST 请求
local res, err = httpc:request({
method = "POST",
path = "/api",
headers = {
["Host"] = host,
["Content-Type"] = "application/json",
["Content-Length"] = #json_body,
},
body = json_body
})
if not res then
ngx.say("failed to request: ", err)
return
end
-- 读取响应
local body, err = res:read_body()
if not body then
ngx.say("failed to read body: ", err)
return
end
-- 关闭连接
local ok, err = httpc:close()
if not ok then
ngx.say("failed to close: ", err)
return
end
-- 输出结果
ngx.say("Status: ", res.status)
ngx.say("Response: ", body)
F&Q
module ‘resty.http’ not found
text
luarocks install lua-resty-http
failed to load module resty.openssl.*, mTLS isn’t supported without lua-resty-openssl
text
luarocks install lua-resty-openssl
lua ssl certificate verify error: (20: unable to get local issuer certificate)