Request():patch()
执行 PATCH 请求并返回一个 Response 对象。此方法用于对服务器上的资源进行部分更新。
签名
patch(): Response
返回值
Response - 包含服务器响应的响应对象
描述
patch() 方法向创建 Request 对象时指定的 URL 发送 HTTP PATCH 请求。PATCH 请求通常用于对现有资源进行部分更新,仅修改请求体中提供的字段。
在调用 patch() 之前,请使用 setParameter() 向请求体添加数据。
示例
基本 PATCH 请求
-- 仅更新用户的 email 字段
local response = Request("https://api.example.com/users/123")
:setParameter("email", "newemail@example.com")
:patch()
带 JSON 请求头的 PATCH 请求
-- 用多个字段部分更新一篇文章
local response = Request("https://api.example.com/posts/456")
:setHeader("Content-Type", "application/json")
:setHeader("Authorization", "Bearer your-token-here")
:setParameter("title", "Updated Post Title")
:setParameter("status", "published")
:patch()
处理 PATCH 响应
-- 更新用户资料并处理响应
local response = Request("https://api.example.com/users/789")
:setHeader("Content-Type", "application/json")
:setHeader("Authorization", "Bearer token123")
:setParameter("bio", "Updated bio information")
:setParameter("website", "https://mywebsite.com")
:patch()
local data = response:getData()
local statusCode = response:getResponseCode()
if statusCode == 200 then
print("User updated successfully!")
print("Updated data: " .. data)
elseif statusCode == 204 then
print("User updated successfully! (No content returned)")
else
print("Failed to update user. Status: " .. statusCode)
end
条件性 PATCH 更新
-- 仅当资源未被修改时才更新
local response = Request("https://api.example.com/articles/123")
:setHeader("Content-Type", "application/json")
:setHeader("If-Match", "etag-value-here")
:setHeader("Authorization", "Bearer token")
:setParameter("content", "Updated article content")
:setParameter("lastModified", "2023-12-01")
:patch()
local status = response:getResponseCode()
if status == 412 then
print("Update failed: Resource has been modified by another user")
elseif status == 200 or status == 204 then
print("Article updated successfully")
end
带字段选择的 PATCH
-- 更新特定字段,同时保持其他字段不变
local response = Request("https://api.example.com/products/456")
:setHeader("Content-Type", "application/json")
:setParameter("price", "29.99")
:setParameter("stock", "150")
:setParameter("discount", "10")
:patch()
local updatedProduct = response:getData()
print("Product updated: " .. updatedProduct)
说明
- 在调用
patch()之前,请使用setParameter()向请求体添加数据 - PATCH 请求应仅包含您要更新的字段,而不是整个资源
- PATCH 与 PUT 的区别在于:PATCH 进行部分更新,而 PUT 替换整个资源
- 成功的 PATCH 操作通常返回:
200 OK,响应体中包含更新后的资源204 No Content,如果更新成功但不需要响应体
- 该方法返回一个 Response 对象,您可以通过它访问响应数据和状态码
- 请始终检查响应状态码,以确保请求成功
- PATCH 请求不一定是幂等的——根据实现不同,多次发起相同的请求可能会产生不同的效果