跳到主要内容

Response:getResponseCode()

从响应中获取 HTTP 状态码。

签名

getResponseCode(): number

返回值

number - HTTP 状态码(例如 200、404、500)

描述

getResponseCode() 方法返回服务器响应中的 HTTP 状态码。状态码指示 HTTP 请求是否成功、失败或需要进一步操作。

示例

基本状态码检查

-- Make a request and check the status code
local response = Request("https://api.example.com/users"):get()
local statusCode = response:getResponseCode()

if statusCode == 200 then
print("Request successful!")
local data = response:getData()
print("Response data: " .. data)
else
print("Request failed with status: " .. statusCode)
end

全面的状态码处理

local response = Request("https://api.example.com/data"):get()
local status = response:getResponseCode()

if status >= 200 and status < 300 then
-- Success responses (2xx)
print("Request successful (2xx)")
local data = response:getData()
print("Data: " .. data)

elseif status >= 300 and status < 400 then
-- Redirection responses (3xx)
print("Redirection received (3xx)")
print("Status: " .. status)

elseif status >= 400 and status < 500 then
-- Client error responses (4xx)
print("Client error (4xx)")
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
end

elseif status >= 500 and status < 600 then
-- Server error responses (5xx)
print("Server error (5xx)")
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Server error details: " .. errorData)
end

else
print("Unexpected status code: " .. status)
end

特定状态码处理

local response = Request("https://api.example.com/users/123"):get()
local status = response:getResponseCode()

if status == 200 then
print("OK - Request successful")
local userData = response:getData()
print("User data: " .. userData)

elseif status == 201 then
print("Created - Resource created successfully")
local newResource = response:getData()
print("New resource: " .. newResource)

elseif status == 204 then
print("No Content - Request successful, no response body")

elseif status == 400 then
print("Bad Request - Invalid request data")
local errorInfo = response:getData()
print("Error: " .. errorInfo)

elseif status == 401 then
print("Unauthorized - Authentication required")

elseif status == 403 then
print("Forbidden - Access denied")

elseif status == 404 then
print("Not Found - Resource does not exist")

elseif status == 500 then
print("Internal Server Error")
local serverError = response:getData()
print("Server error details: " .. serverError)

else
print("Other status: " .. status)
local otherData = response:getData()
if otherData and otherData ~= "" then
print("Response: " .. otherData)
end
end

特定于 HTTP 方法的状态码

-- GET request
local getResponse = Request("https://api.example.com/data"):get()
local getStatus = getResponse:getResponseCode()

if getStatus == 200 then
print("Data retrieved successfully")
elseif getStatus == 404 then
print("Data not found")
end

-- POST request
local postResponse = Request("https://api.example.com/users")
:setParameter("name", "John")
:setParameter("email", "john@example.com")
:post()

local postStatus = postResponse:getResponseCode()

if postStatus == 201 then
print("User created successfully")
local newUser = postResponse:getData()
print("Created user: " .. newUser)
elseif postStatus == 400 then
print("Invalid user data")
elseif postStatus == 409 then
print("User already exists")
end

-- DELETE request
local deleteResponse = Request("https://api.example.com/users/123"):delete()
local deleteStatus = deleteResponse:getResponseCode()

if deleteStatus == 204 then
print("User deleted successfully")
elseif deleteStatus == 404 then
print("User not found")
end

状态码辅助函数

function handleResponse(response)
local status = response:getResponseCode()
local data = response:getData()

-- Success (2xx)
if status >= 200 and status < 300 then
print("✓ Request successful (" .. status .. ")")
if data and data ~= "" then
return data
else
return "Success (no content)"
end
end

-- Client errors (4xx)
if status >= 400 and status < 500 then
print("✗ Client error (" .. status .. ")")
if data and data ~= "" then
print("Error details: " .. data)
end
return nil
end

-- Server errors (5xx)
if status >= 500 and status < 600 then
print("✗ Server error (" .. status .. ")")
if data and data ~= "" then
print("Server error: " .. data)
end
return nil
end

print("? Unexpected status: " .. status)
return nil
end

-- Usage
local response = Request("https://api.example.com/data"):get()
local result = handleResponse(response)

if result then
print("Operation successful: " .. result)
else
print("Operation failed")
end

API 重试逻辑

function makeRequestWithRetry(url, maxRetries)
local retries = 0

while retries < maxRetries do
local response = Request(url):get()
local status = response:getResponseCode()

-- Success
if status == 200 then
return response:getData()
end

-- Don't retry on client errors (4xx)
if status >= 400 and status < 500 then
print("Client error (" .. status .. "), not retrying")
return nil
end

-- Retry on server errors (5xx)
if status >= 500 and status < 600 then
retries = retries + 1
print("Server error (" .. status .. "), retrying... (" .. retries .. "/" .. maxRetries .. ")")
-- Wait before retrying (you might want to add a delay here)
else
retries = retries + 1
print("Unexpected status (" .. status .. "), retrying... (" .. retries .. "/" .. maxRetries .. ")")
end
end

print("Max retries reached, giving up")
return nil
end

local data = makeRequestWithRetry("https://api.example.com/unstable", 3)
if data then
print("Request succeeded: " .. data)
end

常见 HTTP 状态码

代码类别含义典型用法
200成功OK请求成功
201成功Created资源已创建
204成功No Content成功,无响应主体
400客户端错误Bad Request无效的请求数据
401客户端错误Unauthorized需要身份验证
403客户端错误Forbidden拒绝访问
404客户端错误Not Found资源不存在
409客户端错误Conflict资源冲突
500服务器错误Internal Server Error服务器端错误
502服务器错误Bad Gateway无效的上游响应
503服务器错误Service Unavailable服务器暂时不可用

说明

  • 在处理响应数据之前,请始终检查状态码
  • 状态码在 HTTP/1.1 和 HTTP/2 中是标准化的
  • 2xx 代码表示成功,3xx 表示重定向,4xx 表示客户端错误,5xx 表示服务器错误
  • 某些 API 可能使用自定义状态码或非标准的含义
  • 错误响应(4xx、5xx)的响应主体中可能包含有用的信息
  • 网络错误或超时可能会完全阻止响应对象的创建