openresty发起http外部请求
1)安装lua-resty-http
opm get agentzh/lua-resty-http
2)编辑nginx.conf,在http块增加以下配置。
resolver 114.114.114.114 8.8.8.8;
lua_ssl_verify_depth 2;
lua_ssl_trusted_certificate '/etc/ssl/certs/ca-certificates.crt';
备注:如果/etc/ssl/certs/ca-certificates.crt不存在,则安装ca-certificates(例:apt-get install ca-certificates)。
3)代码示例
local http = require "resty.http"
local json = require "cjson"
local httpc = http:new()
local res, err = httpc:request_uri("http://127.0.0.1:80/", {
method = "POST/GET",
query = "a=1&b=2",
body = "c=3&d=4",
path = "/",
headers = {
["Content-Type"] = "application/json",
-- ["Content-Type"] = "application/x-www-form-urlencoded",
["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
},
ssl_verify = false,
})
if err ~= nil then
ngx.log(ngx.ERR, "http request err:", err)
return ngx.exit(0)
end
if 200 ~= res.status then
ngx.exit(res.status)
end
local jsondata = json.decode(res.body)["data"]
httpc:close()
-- httpc:set_keepalive()