OpenResty默认没有提供Http客户端,需要使用第三方提供的插件
我们可以从github上搜索相应的客户端,比如https://github.com/pintsized/lua-resty-http 安装方法:将 lua-resty-http/lib/resty/ 目录下的 http.lua 和 http_headers.lua
两个文件拷贝到 /usr/local/openresty/lualib/resty 目录下即可
(假设 OpenResty 安装目录为 /usr/local/openresty) 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模块
local http = require("resty.http")
--创建http客户端实例
local httpc = http:new() local resp,err = httpc:request_uri("https://list.tmall.com",
{
method = "GET", ---请求方式
--path="/search_product.htm?q=ipone",
query="q=iphone", ---get方式传参数
body="name='jack'&age=18", ---post方式传参数
path="/search_product.htm", ----路径
---header参数
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
if type(v) == "table" then
ngx.log(ngx.WARN,"table:"..k, ": ", table.concat(v, ", "))
else
ngx.log(ngx.WARN,"one:"..k, ": ", v)
end
end
ngx.say("end")
--响应体
ngx.say(resp.body) httpc:close() httpc:close() # 后台日志
# /usr/local/openresty/nginx]# tail -f logs/debug.log
// :: [warn] #: * [lua] testhttp02.lua:: one:ufe-result: A6, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Date: Fri, Aug :: GMT, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Location: https://login.taobao.com/jump?target=https%3A%2F%2Flist.tmall.com%2Fsearch_product.htm%3Ftbpm%3D1%26q%3Diphone, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Connection: keep-alive, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:EagleEye-TraceId: 0bfa16f315665542845385751e42fa, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Strict-Transport-Security: max-age=, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Content-Length: , client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Timing-Allow-Origin: *, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"
// :: [warn] #: * [lua] testhttp02.lua:: one:Server: Tengine/Aserver, client: 192.168.10.164, server: www.server1.com, request: "GET /testhttp02 HTTP/1.1", host: "192.168.10.164"

-------------------------------------------------------
发现报错
request error :no resolver defined to resolve "list.tmall.com" 此错误是因为要配置DNS解析器resolver 8.8.8.8,否则域名是无法解析的。
在nginx.conf配置文件中 http模块加上resolver 8.8.8.8; Google提供的免费DNS服务器的IP地址
配置好后,重启nginx --------------------------------------------------------- 访问https错误,因为我们访问的https,需要配置ssl证书
在nginx配置文件中,server虚拟主机模块设置 lua_ssl_verify_depth ;
lua_ssl_trusted_certificate "/etc/ssl/certs/ca-bundle.crt"; -------------------------------------------------------- http模块应用场景很多,这里只简单介绍了一下http模块的使用 还有很多openresty模块,可以参考 https://github.com/bungle/awesome-resty 以suning.com为例: 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()

配置示例

# cat /usr/local/openresty/nginx/conf/nginx.conf
worker_processes ; #pid logs/nginx.pid;
events {
worker_connections ;
} http {
include mime.types;
default_type text/html; sendfile on;
keepalive_timeout ;
resolver 8.8.8.8; server {
listen ;
server_name www.server1.com;
lua_ssl_verify_depth ;
lua_ssl_trusted_certificate "/etc/ssl/certs/ca-bundle.crt"; location /tmall {
access_by_lua_file /usr/local/lua/tmall.lua;
} location / {
root html;
index index.html index.htm;
} error_page /50x.html;
location = /50x.html {
root html;
} } }

lua脚本

# cat /usr/local/lua/tmall.lua
--引入http模块
local http = require("resty.http")
--创建http客户端实例
local httpc = http:new() local resp,err = httpc:request_uri("https://list.tmall.com",
{
method = "GET", ---请求方式
--path="/search_product.htm?q=ipone",
query="q=iphone", ---get方式传参数
body="name='jack'&age=18", ---post方式传参数
path="/search_product.htm", ----路径
---header参数
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
if type(v) == "table" then
ngx.log(ngx.WARN,"table:"..k, ": ", table.concat(v, ", "))
else
ngx.log(ngx.WARN,"one:"..k, ": ", v)
end
end
ngx.say("end")
--响应体
ngx.say(resp.body) httpc:close()

openresty开发系列30--openresty中使用http模块的更多相关文章

  1. openresty开发系列36--openresty执行流程之6日志模块处理阶段

    openresty开发系列36--openresty执行流程之6日志模块处理阶段 一)header_filter_by_lua 语法:header_filter_by_lua <lua-scri ...

  2. openresty开发系列30--openresty中使用全局缓存

    openresty开发系列30--openresty中使用全局缓存 Nginx全局内存---本地缓存 使用过如Java的朋友可能知道如Ehcache等这种进程内本地缓存.Nginx是一个Master进 ...

  3. openresty开发系列29--openresty中发起http请求

    openresty开发系列29--openresty中发起http请求 有些场景是需要nginx在进行请求转发 用户浏览器请求url访问到nginx服务器,但此请求业务需要再次请求其他业务:如用户请求 ...

  4. openresty开发系列28--openresty中操作mysql

    openresty开发系列28--openresty中操作mysql Mysql客户端   应用中最常使用的就是数据库了,尤其mysql数据库,那openresty lua如何操作mysql呢?   ...

  5. openresty开发系列27--openresty中封装redis操作

    openresty开发系列27--openresty中封装redis操作 在关于web+lua+openresty开发中,项目中会大量操作redis, 重复创建连接-->数据操作-->关闭 ...

  6. openresty开发系列26--openresty中使用redis模块

    openresty开发系列26--openresty中使用redis模块 在一些高并发的场景中,我们常常会用到缓存技术,现在我们常用的分布式缓存redis是最知名的, 操作redis,我们需要引入re ...

  7. openresty开发系列25--openresty中使用json模块

    openresty开发系列25--openresty中使用json模块 web开发过程中,经常用的数据结构为json,openresty中封装了json模块,我们看如何使用 一)如何引入cjson模块 ...

  8. openresty开发系列24--openresty中lua的引入及使用

    openresty开发系列24--openresty中lua的引入及使用 openresty 引入 lua 一)openresty中nginx引入lua方式 1)xxx_by_lua   ---> ...

  9. openresty开发系列16--lua中的控制结构if-else/repeat/for/while

    openresty开发系列16--lua中的控制结构if-else/repeat/for/while 一)条件 - 控制结构 if-else if-else 是我们熟知的一种控制结构.Lua 跟其他语 ...

  10. openresty开发系列40--nginx+lua实现获取客户端ip所在的国家信息

    openresty开发系列40--nginx+lua实现获取客户端ip所在的国家信息 为了实现业务系统针对不同地区IP访问,展示包含不同地区信息的业务交互界面.很多情况下系统需要根据用户访问的IP信息 ...

随机推荐

  1. pandas速查手册(中文版)

    本文翻译自文章:Pandas Cheat Sheet - Python for Data Science 对于数据科学家,无论是数据分析还是数据挖掘来说,Pandas是一个非常重要的Python包.它 ...

  2. 安装k8s,单master脚本

    这个以一个普通xxx帐户运行即可. 因为上面root帐号作了sudoer的操作的. 还有,最好将xxx帐号加入docker组,这样xxx也可以执行docker命令了. 可以看到,这个脚本还需要其它目录 ...

  3. LFU(最近最不常用)实现(python)

    from collections import defaultdict, OrderedDict class Node: __slots__ = 'key', 'val', 'cnt' def __i ...

  4. mac pro下安装brew软件包管理工具

    Homebrew简称brew,OSX上的软件包管理工具,在Mac终端可以通过brew安装.更新.卸载软件. 1.打开终端直接输入下面指令回车: ruby -e "$(curl -fsSL h ...

  5. test20190815 NOIP2019 模拟题

    100+60+40=200,被后面两个题卡着我很不爽. 立方数 [问题描述] 作为 XX 战队的狂热粉丝,MdZzZZ 看到了自己心仪的队伍在半决赛落败,顿时 心灰意冷.看着自己手中的从黄牛那里抢来的 ...

  6. ORACLE11g:No Dialect mapping for JDBC type: -9解决方案

    问题来源: 某个zhizhang同事不干活 好不容易干了个活 改了个字段长度,从varchar2(50) 改成了nvarchar(100) 结果因为方言问题,程序起不来了 字段类型也改不回来了 nnd ...

  7. LightOJ-1275-Internet Service Providers(数学)

    链接: https://vjudge.net/problem/LightOJ-1275 题意: A group of N Internet Service Provider companies (IS ...

  8. Hbase节点及原理

    1.Hbase架构:Clinet.Zookeeper.Master.RegionServer.Region.Store.MemStore.HLog 1.读过程 2.写过程 https://www.cn ...

  9. Tensorflow细节-P174-真正的图像预处理

    注意这里的读取image_raw_data = tf.gfile.FastGFile("./datasets/cat.jpg", "rb").read(),写入 ...

  10. 计蒜客模拟赛 #5 (B 题) 动态点分治+线段树

    虽然是裸的换根dp,但是为了在联赛前锻炼码力,强行上了点分树+线段树. 写完+调完总共花了不到 $50$ 分钟,感觉还行. code: #include <bits/stdc++.h> # ...