【问题标题】:Capture full response in Lua Socket call在 Lua Socket 调用中捕获完整响应
【发布时间】:2017-07-12 14:12:49
【问题描述】:

我正在尝试通过 LUA 调用 REST API。但是,我无法捕获 API 返回的完整原始响应。下面是代码示例:

local http_socket = require("socket.http")
local pretty_print = require("pl.pretty")
local header = {
                 ["x-device-type"] = "M",
                 ["authorization"] = "ashdjkashd",
                 ["x-app-secret"] = "asdasda",
                 ["x-user-id"] = "asdasdasd"
                 }

r, c, h = http_socket.request {
       method = "GET",                          -- Validation API Method                           
       url = "http://google.com",   -- Validation API URL
       headers = header
}
print(r .. c)
pretty_print.dump(h)

我使用的是 lua 5.3,luarocks 版本=2.4.1。 在变量 c 中我得到代码,在 h 中有一些标题。我需要捕获 API 返回的完整响应。

【问题讨论】:

    标签: lua luasocket luarocks


    【解决方案1】:

    如你所知,luasocket 的http.request 支持two forms of usage。我假设您需要第二种形式来自定义该特定 API 的 resty 请求。

    在这种情况下,要捕获响应正文,您需要将 sink 字段与 ltn12.sink 模块一起使用。例如

    local ltn12 = require 'ltn12'
    
    -- ...
    
    local res = {}
    r, c, h, s = http_socket.request
    {
      method = "GET",               -- Validation API Method
      url = "http://google.com",    -- Validation API URL
      headers = header,
      sink = ltn12.sink.table(res)
    }
    
    res = table.concat(res)
    print(res)
    

    需要table.concat,因为响应可能包含多个块大小(在收到时附加到res)。

    您也可以将上面的内容替换为ltn12.sink.file,例如,将其写入文件。使用ltn12.sink.file(io.stdout) 会将响应转储到标准输出。

    【讨论】:

    • 非常感谢!像魅力一样工作。
    • 我错过了table.concat。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 2019-06-29
    • 2023-03-05
    • 1970-01-01
    • 2021-03-24
    • 2020-08-01
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多