在lua中操作http请求有两种方式
HTTP 操作 方式 请求 两种 lua
2023-09-27 14:29:10 时间
第一种方式:使用通过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连接池配置一致。
相关文章
- curl模拟Http请求
- Node进阶:核心模块http简介
- IIS7.5上的REST服务的Put操作发生HTTP Error 405.0 - Method Not Allowed 解决方法
- Linux有问必答:如何在curl中设置自定义的HTTP头
- http://blog.csdn.net/gobitan/article/details/1809763
- Http的操作(不传递参数)
- 区分http请求状态码来理解缓存(协商缓存和强制缓存)
- NGINX Load Balancing - HTTP Load Balancer
- 《计算机网络:自顶向下方法(原书第6版)》一2.2 Web和HTTP
- CentOS7下HTTP并发测试工具Apache Benchmark(AB)安装和使用
- 解决“HTTP/1.1 405 Method not allowed”问题
- nginx中proxy_set_header Host $host的作用及$proxy_host,$host与$http_host的区别
- 使用Paros监控iPhone发出的HTTP请求
- odoo13 WARNING zheng0519 odoo.http: (‘记录不存在或已被删除。n(记录: res.country(16,
- 【树莓派】 Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/c/chkconfig/chkconfig_11.4.54.60.1debian1_all.deb Could not resolve 'mirrordirector.raspbian.org'
- Docker介绍以及Registry的安装 -摘自http://dockone.io/article/108
- iOS AFNetwork实现Http相关操作(NetReachable、Get、Post、Upload、Download)