如何使用LuaSec在Lua中正确发送POST数据?
问题描述
尝试在Lua中通过LuaSec发送JSON格式POST数据,按示例操作后无数据发送,GET请求也存在同类问题。怀疑ltn12使用方式有误,测试代码如下:
local ltn12 = require('ltn12') local https = require('ssl.https') local json = require("json") local body = json.encode({ test = "test ok" }) local r = {} https.request { url = 'https://httpbin.org/anything', method = "POST", headers = {["Content-Type"] = "application/json"}, source = ltn12.source.string(body), sink = ltn12.sink.table(r) } print(r[1])
返回结果中data字段为空:
{ "args": {}, "data": "", "files": {}, "form": {}, "headers": { "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "LuaSocket 3.0-rc1", "X-Amzn-Trace-Id": "..." }, "json": null, "method": "POST", "origin": "XX.XX.XX.XX", "url": "https://httpbin.org/anything" }
问题原因与解决办法
核心问题是未在请求头中添加Content-Length字段。LuaSec搭配ltn12的组合不会自动计算并设置请求体长度,服务器无法知晓需要读取多少数据,导致接收为空。
只需在headers中添加Content-Length,值为JSON字符串的长度即可:
修正后的完整代码:
local ltn12 = require('ltn12') local https = require('ssl.https') local json = require("json") local body = json.encode({ test = "test ok" }) local r = {} local res, code, headers, status = https.request { url = 'https://httpbin.org/anything', method = "POST", headers = { ["Content-Type"] = "application/json", ["Content-Length"] = tostring(#body) -- 新增Content-Length头 }, source = ltn12.source.string(body), sink = ltn12.sink.table(r) } print(r[1])
此时httpbin返回的结果中,data和json字段会正确显示发送的内容:
{ "args": {}, "data": "{\"test\":\"test ok\"}", "files": {}, "form": {}, "headers": { "Content-Length": "17", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "LuaSocket 3.0-rc1", "X-Amzn-Trace-Id": "..." }, "json": { "test": "test ok" }, "method": "POST", "origin": "XX.XX.XX.XX", "url": "https://httpbin.org/anything" }
内容的提问来源于stack exchange,提问作者pguimier
相关产品推荐
相关产品推荐

