[英]lua - How to send POST data properly using luasec?
我正在尝试使用 luasec 在 lua 中发布一些 json 数据,但是在下面的示例中,似乎没有发送任何数据。 它甚至发生在 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])
结果如下:
{
"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"
}
“数据”字段为空。
回答自己,问题解决了。 这不是 luasec 问题,事情与 socket.http 类似。
所以正确的代码是:
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",
["Content-Length"] = #body
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(r)
}
print(r[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.