openresty本身要发起http请求是一件比较麻烦的事情,还好有春哥写了个lua_resty_http,让openresty发起http请求更容易。
我使用的是其中一个分支:https://github.com/pintsized/lua-resty-http
git clone https://github.com/pintsized/lua-resty-http
下载到openresty安装的目录下后,接着在nginx.conf中添加lua文件的路径:"/data/apiserver/lua-resty-http/lib/?.lua;;";
另外再添加一个location:
location /test {
content_by_lua_file scripts/test.lua ;
}
再看test.lua文件:
ngx.header.content_type = "application/json;charset=UTF-8"
local json = require "cjson"
local http = require "resty.http"
local httpc = http:new()
local url = "http://api.xxxx.com/"
local res, err = httpc:request_uri(url, {
method = "POST",
body = "appid=20170412&secret=11111",
-- query = {
-- appid = "20170412", --填写自己的appid
-- secret = "zbb", -- 填写自己的secret
-- },
ssl_verify = false, -- 需要关闭这项才能发起https请求
headers = {["Content-Type"] = "application/x-www-form-urlencoded" },
})
if not res then
ngx.say("failed to request: ", err)
return
end
ngx.say(json.encode({code=res.status,message=res.body}))