Response
Response 对象包含使用 Request 模块发出的 HTTP 请求的结果。它提供了对服务器返回的响应数据、状态码以及其他元数据的访问。
概述
Response 对象由 get()、post()、put()、patch() 和 delete() 等 HTTP 请求方法返回。它们封装了服务器的响应,并提供了访问响应内容和元数据的方法。
方法
getData(): string
以字符串形式获取响应主体内容。
返回值
string - 响应主体内容
getResponseCode(): number
从响应中获取 HTTP 状态码。
返回值
number - HTTP 状态码(例如 200、404、500)
常见用法模式
-- Make a request and handle the response
local response = Request("https://api.example.com/data"):get()
-- Get the status code to check if the request was successful
local statusCode = response:getResponseCode()
if statusCode == 200 then
-- Request was successful, get the data
local data = response:getData()
print("Response data: " .. data)
else
-- Request failed, handle the error
print("Request failed with status: " .. statusCode)
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
end
end
HTTP 状态码分类
| 状态码范围 | 含义 | 典型响应 |
|---|---|---|
| 200-299 | 成功 | 包含请求的数据或确认信息 |
| 300-399 | 重定向 | 通常为空或包含重定向信息 |
| 400-499 | 客户端错误 | 包含错误描述 |
| 500-599 | 服务器错误 | 包含错误描述 |
响应数据格式
无论原始格式如何,响应数据始终以字符串形式返回:
- JSON:
"{\"key\":\"value\"}"- 如果您有 JSON 解析器,可能需要进行解析 - XML:
"<?xml version=\"1.0\"?><root>...</root>"- 作为字符串的 XML 内容 - 纯文本:
"Simple text response"- 直接的文本内容 - HTML:
"<html><body>...</body></html>"- 作为字符串的 HTML 内容 - 空:
""- 没有内容(常见于 204 响应)
最佳实践
- 在处理响应数据之前,始终先检查状态码
- 妥善处理空响应,尤其是 204 状态码的响应
- 即使对于错误响应也要检查响应内容,因为其中可能包含有用信息
- 为可能出现的网络错误做好准备,这些错误可能会阻止响应对象的创建
示例
基本响应处理
local response = Request("https://api.example.com/users/123"):get()
local status = response:getResponseCode()
if status == 200 then
local userData = response:getData()
print("User data: " .. userData)
else
print("Failed to get user data. Status: " .. status)
end
错误处理
local response = Request("https://api.example.com/invalid"):get()
local status = response:getResponseCode()
if status == 404 then
print("Resource not found")
elseif status == 401 then
print("Authentication required")
elseif status >= 500 then
print("Server error: " .. status)
local errorDetails = response:getData()
print("Error details: " .. errorDetails)
else
print("Unexpected status code: " .. status)
end
使用不同的 HTTP 方法
-- GET request
local getResponse = Request("https://api.example.com/data"):get()
print("GET status: " .. getResponse:getResponseCode())
-- POST request
local postResponse = Request("https://api.example.com/data")
:setParameter("key", "value")
:post()
print("POST status: " .. postResponse:getResponseCode())
-- DELETE request
local deleteResponse = Request("https://api.example.com/data/123"):delete()
print("DELETE status: " .. deleteResponse:getResponseCode())