【问题标题】:lua - How to send POST data properly using luasec?lua - 如何使用 luasec 正确发送 POST 数据?
【发布时间】:2023-01-27 17:44:59
【问题描述】:

我正在尝试使用 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"
}

“数据”字段为空。

【问题讨论】:

    标签: post https lua luasec


    【解决方案1】:

    回答自己,问题解决了。这不是 luasec 问题,事情与 socket.http 类似。

    • 发送的body有“content-type: application/json”,所以数据是json字段,不是data字段。
    • 标题需要数据的大小

    所以正确的代码是:

    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])
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2015-12-22
      • 2023-03-25
      • 2019-04-27
      • 1970-01-01
      • 2011-04-19
      • 2022-01-03
      • 2022-01-21
      • 2019-08-09
      相关资源
      最近更新 更多