实用工具

request

发送带有方法、标头、正文和超时选项的 HTTP 请求。

语法

request(options: RequestOptions): Response | string
别名 http_requesthttp.request

参数

名称类型描述
optionsRequestOptions控制操作行为方式的可选设置表。

返回值

名称类型描述
responseResponse | stringHTTP 响应表或兼容性字符串。

说明

发送带有方法、标头、正文和超时选项的 HTTP 请求。

使用 1 个参数调用: options。参数表会说明哪些值必填,哪些值只用于细化行为。

返回 response (Response | string)。使用返回表区分成功值、nil 结果和可恢复错误。

示例

发送 JSON 请求并检查公共响应字段。

local response = request({
    Url = "https://example.com/api/status",
    Method = "GET",
    Headers = {
        ["Accept"] = "application/json",
    },
})

if type(response) == "table" then
    if response.Success then
        print(response.StatusCode, response.Body)
    else
        warn(response.StatusMessage)
    end
else
    warn(response)
end

类型

RequestOptions

定义 HTTP 请求。

Url string HTTP 或 HTTPS 目标 URL。Method? "GET" | "POST" | "PUT" | "PATCH" | "DELETE" 用于请求的 HTTP 方法。Headers? {[string]: string} 附加请求标头。Cookies? {[string]: string} 添加到传出请求的 Cookie。Body? string 原始请求正文。