Lua POST 请求包含垃圾

Lua POST request contains garbage

我正在尝试发送 POST 请求,但发现我尝试访问的端点似乎不喜欢该请求,因此为了调查情况,我将请求重定向到 localhost 在用 nc 收听时看到以下请求:

nc -vlp 444

Connection from 127.0.0.1:53812
POST / HTTP/1.1
Host: localhost:4444
TE: trailers
Cookie: 
Content-Type: application/x-www-form-urlencoded
Connection: close, TE
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0

27 -- this line shouldn't be there
username=username&password=password
0  -- also this one

我正在使用的代码,以防万一:


local http = require("socket.http") -- even tried ssl.https

...

function Session:post(url, payload) -- payload = "username=username&password=password"
    local response = Response
    local body = { }
    local r, c, h, s = http.request{
        url = url,
        method = "POST",
        sink = ltn12.sink.table(body),
        source = ltn12.source.string(payload),
        headers = {
            ["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0",
            ["Content-Type"] = "application/x-www-form"
        },
    }
    -- you can ignore this
    response.code    = c
    response.status  = s
    response.body    = table.concat(body)
    self.cookies:parse(h["set-cookie"])
    return response
end

以为是ltn12的问题,直接把它的源代码复制到我的项目中,但很快发现它只返回了payload,并没有真正改变任何东西

BLOCKSIZE = 2048
function generate_payload(s)
    if s then
        local i = 1
        return function()
            local chunk = string.sub(s, i, i+BLOCKSIZE-1)
            i = i + BLOCKSIZE
            if chunk ~= "" then return chunk
            else return nil end
        end
    else return source.empty() end
end

通过添加 Content-Length header 设法解决了问题。