lua resty.http 代理请求时加号变成空格处理方法

铺垫知识

+号在http传输中,会转为空格,所以需要额外转义,转为%2B就可以了。

现象描述

今天遇到很奇怪的现象,前端web页面传过来的时间戳是 2020-12-08T00:00:00+08:00 ,我在nginx+lua里面使用 resty.http 来转发请求的时候,发现到服务器端的时间是这样的:2020-12-08T00:00:00 08:00 , 显然,00与08之间的加号没了,转为了空格。

解决办法

在lua代码里面,把+号都替换成%2B ,如

local http = require("resty.http")
local httpc = http.new()

.... 省去获取参数的代码

local new_post_data = ""
for k,v in pairs(post_data) do
    if type(v) == "string" then
        if string.find(v,"Date") ~= nil then  -- v这个是前端传过来的值,
            v = string.gsub(v,"%+08","%%2B08")  -- 关键点,转换空格 
        end
    end
    new_post_data = new_post_data .. k .. "=" .. v .. "&"
done

local post_body_len = string.len(post_body)
body = string.sub(post_body,0,post_body_len-1)  -- 去掉最后一位与符号&
res,err = httpc:request_uri(url, {
    method = method, -- POST 
    body = body,
    headers = headers, -- 自己定义一个吧
    keepalive_timeout = 60000,  -- ms
})

这样到了服务器端,就没问题了。

posted @ 2020-12-08 14:58  温柔易淡  阅读(679)  评论(0编辑  收藏  举报