0

I'm trying to POST some json datas in lua with luasec, but while following examples, it looks like no data is sent. It occurs even with GET requests. Maybe I'm not using ltn12 correctly ?

Here is the code I tried :

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

And here's the result :

{
  "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"
}

The "data" field is empty.

pguimier
  • 1
  • 1

1 Answers1

0

Answering myself, problem solved. It is not a luasec issue, things are similar with socket.http.

  • The body sent has "content-type: application/json", so the data is in json field, not in data field.
  • headers needs a size of the datas

So the correct code is :

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])
pguimier
  • 1
  • 1