在lua中操作http请求有两种方式

第一种方式:使用通过ngx.location.capture 去方式实现,但是有一些限制
第二种方式:因为openresty默认没有引入第三方http客户端类库lua-resty-http,需要下载(推荐)。

下载lua-resty-http类库

wget https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty/http_headers.lua
wget https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty/http.lua
wget https://github.com/ledgetech/lua-resty-http/blob/master/lib/resty/http_connect.lua

 lua-resty-http语法:

local res, err = httpc:request_uri(uri, {  
    method = "POST/GET",  ---请求方式
    query = str,  ---get方式传参数
    body = str,     ---post方式传参数
    path = "url" ----路径
    headers = {  ---header参数
        ["Content-Type"] = "application/json",  
    }  
})

 

把http_headers.lua、http.lua、http_connect.lua文件放在D:\dev\openresty-1.19.9.1\lualib\resty目录,有重复直接覆盖。

location /test {
    default_type text/html;
    content_by_lua_file lua/http_test.lua;
}

 

D:\dev\openresty-1.19.9.1\lua\http_test.lua,内容如下:

local http = require("resty.http")
--创建http客户端实例
local httpc = http:new()

local resp,err = httpc:request_uri("http://issm.suning.com",
{
    method = "GET",
    path="/productDetail_P11271.htm",
    headers = {["User-Agent"]="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"}
})
if not resp then
    ngx.say("request error:",err)
    return
end
--获取状态码
ngx.status = resp.status

--获取响应信息
--响应头中的Transfer-Encoding和Connection可以忽略,因为这个数据是当前server输出的。
for k,v in pairs(resp.headers) do
    if k ~= "Transfer-Encoding" and k ~= "Connection" then
        ngx.header[k] =v
    end
end

--响应体
ngx.say(resp.body)

httpc:close()

 

注意:需要在http模块中添加如下指令来做DNS解析,不然会报出解析域名错误,如下:

2022/08/26 09:33:21 [info] 8248#21972: *277 client timed out (10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) while waiting for request, client: 127.0.0.1, server: 0.0.0.0:80

解决办法:resolver 8.8.8.8;

其http客户端也支持连接池,与redis、mysql连接池配置一致。

posted on 2022-08-26 10:03  Ruthless  阅读(7997)  评论(0编辑  收藏  举报