跳到主要内容

Request():setHeader()

为 HTTP 请求设置新的请求头。此方法允许您在发送请求之前为其添加自定义 HTTP 请求头。

签名

setHeader(key: string, value: string): Request

参数

参数类型说明
keystring请求头名称
valuestring请求头的值

返回值

Request - 返回 Request 对象,以便进行方法链式调用

描述

setHeader() 方法向请求添加自定义 HTTP 请求头。请求头是元数据,用于提供有关请求的附加信息,例如内容类型、授权信息或用户代理。您可以多次调用此方法以添加多个请求头。

示例

设置授权请求头

--API 身份认证添加 Bearer 令牌
local response = Request("https://api.example.com/data")
:setHeader("Authorization", "Bearer your-token-here")
:get()

设置内容类型

--POST 请求设置 JSON 内容类型
local response = Request("https://api.example.com/users")
:setHeader("Content-Type", "application/json")
:setParameter("name", "John Doe")
:setParameter("email", "john@example.com")
:post()

多个请求头

-- 为请求设置多个请求头
local response = Request("https://api.example.com/protected")
:setHeader("Authorization", "Bearer token123")
:setHeader("Content-Type", "application/json")
:setHeader("Accept", "application/json")
:setHeader("User-Agent", "MyApp/1.0")
:get()

自定义请求头

-- 添加应用程序专用的自定义请求头
local response = Request("https://api.example.com/process")
:setHeader("X-API-Key", "your-api-key")
:setHeader("X-Request-ID", "unique-request-identifier")
:setHeader("X-Client-Version", "2.1.0")
:post()

表单数据请求头

-- 设置表单数据提交的请求头
local response = Request("https://example.com/login")
:setHeader("Content-Type", "application/x-www-form-urlencoded")
:setParameter("username", "user")
:setParameter("password", "pass")
:post()

常见 HTTP 请求头

请求头名称典型用途示例
Authorization身份认证令牌"Bearer token123"
Content-Type请求体格式"application/json"
Accept响应格式偏好"application/json"
User-Agent客户端标识"MyApp/1.0"
X-API-KeyAPI 身份认证"your-api-key"
Content-Length请求体大小(通常自动设置)"256"

说明

  • 请求头不区分大小写,但通常使用 Header-Case 命名惯例(例如 Content-Type
  • 该方法返回 Request 对象,允许进行方法链式调用
  • 某些请求头可能由 HTTP 客户端自动设置
  • 某些请求头(如 Content-Length)通常会自动计算
  • 请谨慎处理身份认证请求头,不要泄露敏感信息
  • 您可以通过多次设置相同的请求头名称来覆盖请求头