lua发送带http post 带多个参数请求并解析后台响应json数据
lua发送带http post 带多个参数请求并解析后台响应json数据
原文链接:https://blog.csdn.net/weixin_44259356/article/details/96483501
公司要求kong网关从后台读取用户权限数据,特此记录开发,主要分为两个部分:1发送http请求,2解析后台响应json。项目源码已托管github
https://github.com/MyRong12138/http-service
lua发送http post带多个参数请求
kong 自带resty.http库,如果是lua直接使用可能还需要下载库文件。话不多说上代码
获取请求路径信息
local function parse_url(host_url)
local parsed_url
parsed_url = url.parse(host_url)
if not parsed_url.port then
if parsed_url.scheme == "http" then
parsed_url.port = 80
elseif parsed_url.scheme == "https" then
parsed_url.port = 443
end
end
if not parsed_url.path then
parsed_url.path = "/"
end
return parsed_url
end
发送请求
local function send_payload(url,body)
local getRequestUrl=parse_url(url)
local host = getRequestUrl.host
local port = tonumber(getRequestUrl.port)
local httpc = http.new()
httpc:set_timeout(60000)
ok, err = httpc:connect(host, port)
if not ok then
return nil, "failed to connect to " .. host .. ":" .. tostring(port) .. ": " .. err
end
if getRequestUrl.scheme == "https" then
local _, err = httpc:ssl_handshake(true, host, false)
if err then
return nil, "failed to do SSL handshake with " ..
host .. ":" .. tostring(port) .. ": " .. err
end
end
local res, err = httpc:request({
method = "POST",
path = getRequestUrl.path,
query = getRequestUrl.query,
headers = {
["Host"] = getRequestUrl.host,
["Content-Type"] = "application/x-www-form-urlencoded",
["Authorization"] = getRequestUrl.userinfo and (
"Basic " .. ngx_encode_base64(getRequestUrl.userinfo)
),
},
body = body,
})
if not res then
return nil, "failed request to " .. host .. ":" .. tostring(port) .. ": " .. err
end
local response_body = res:read_body()
local success = res.status == 200
local err_msg
if not success then
err_msg = "request to " .. host .. ":" .. tostring(port) ..
" returned status code " .. tostring(res.status) .. " and body " ..
response_body
end
ok, err = httpc:set_keepalive(keepalive)
if not ok then
kong.log.err("failed keepalive for ", host, ":", tostring(port), ": ", err)
end
return response_body,err_msg
end
解析json
使用cjson库,如果没有用过的话,通过LuaRocks安装
安装cjson
搜索cjson版本
luarocks earch cjson
安装cjson,xxx为版本号
luarocks install cjson-xxx
使用cjson解析json
解析json
function get_json(body)
local cjson = require("cjson")
local json=cjson.new()
kong.log("解析json开始")
local table = json.decode(body)
if table ~= nil and next(table) ~= nil then
kong.log("取得json"..tostring(table))
end
for k, v in pairs(table["RoleList"]) do
--print(k .. " : " .. v)
kong.log("\njson存储的值名为:"..k.."\n值为:"..tostring(v).."\n")
end
end