随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

在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   Ruthless  阅读(10673)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
历史上的今天:
2020-08-26 Java使用Aspose-Words实现Word转换Pdf
2020-08-26 在linux环境下com.aspose.words将word文件转为pdf后乱码,window环境下不会
2017-08-26 Disruptor入门
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示