跳到主要内容

Response:getData()

以字符串形式从 HTTP 响应中获取响应主体内容。

签名

getData(): string

返回值

string - 以字符串形式返回的响应主体内容

描述

getData() 方法从 HTTP 响应中检索响应主体内容。无论原始格式是什么(JSON、XML、纯文本、HTML 等),内容始终以字符串形式返回。

示例

基本用法

-- Make a GET request and get the response data
local response = Request("https://api.example.com/users"):get()
local userData = response:getData()
print("User data: " .. userData)

处理 JSON 数据

-- Get JSON response data
local response = Request("https://api.example.com/posts/1"):get()
local jsonData = response:getData()

-- jsonData will be a string like: "{\"id\":1,\"title\":\"Sample Post\",\"body\":\"Content\"}"
print("Raw JSON: " .. jsonData)

-- Note: You would need a JSON parser to convert this string to a Lua table
-- For example (if you have a JSON parser available):
-- local parsedData = json.decode(jsonData)
-- print("Post title: " .. parsedData.title)

处理 XML 响应

-- Get XML response data
local response = Request("https://api.example.com/data.xml"):get()
local xmlData = response:getData()

-- xmlData will contain XML content as a string
if xmlData and xmlData ~= "" then
print("XML data received: " .. xmlData)
-- You would need an XML parser to process this data
end

错误响应数据

-- Make a request that might fail
local response = Request("https://api.example.com/invalid"):get()
local statusCode = response:getResponseCode()

if statusCode ~= 200 then
-- Get error details from response body
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
else
print("No error details provided")
end
end

POST 请求响应数据

-- Create a resource and get the response
local response = Request("https://api.example.com/users")
:setParameter("name", "John Doe")
:setParameter("email", "john@example.com")
:post()

local status = response:getResponseCode()
local responseData = response:getData()

if status == 201 then
print("User created successfully!")
print("Created user data: " .. responseData)
else
print("Failed to create user. Status: " .. status)
if responseData then
print("Error: " .. responseData)
end
end

空响应处理

-- Handle responses that might be empty
local response = Request("https://api.example.com/delete/123"):delete()
local status = response:getResponseCode()
local data = response:getData()

if status == 204 then
-- No content response
print("Delete successful (no content returned)")
if data == "" or not data then
print("Response is empty as expected")
end
elseif status == 200 then
print("Delete successful with response: " .. data)
else
print("Delete failed with status: " .. status)
end

处理不同的内容类型

-- Check Content-Type header if available (this would require accessing response headers)
-- For now, we can detect common patterns in the data
local response = Request("https://api.example.com/data"):get()
local data = response:getData()

if data and data ~= "" then
-- Detect JSON format
if string.sub(data, 1, 1) == "{" or string.sub(data, 1, 1) == "[" then
print("Received JSON data")
-- Process as JSON
-- Detect XML format
elseif string.find(data, "^<%?xml") or string.find(data, "^<[^>]+>") then
print("Received XML data")
-- Process as XML
-- Detect HTML format
elseif string.find(data, "^<html") or string.find(data, "^<!DOCTYPE") then
print("Received HTML data")
-- Process as HTML
else
print("Received plain text data")
-- Process as plain text
end

print("Data length: " .. string.len(data) .. " characters")
else
print("No data received")
end

大型响应处理

-- Handle potentially large responses
local response = Request("https://api.example.com/large-data"):get()
local data = response:getData()

if data then
local dataSize = string.len(data)
print("Received " .. dataSize .. " characters of data")

if dataSize > 10000 then
print("Large response detected - first 100 characters:")
print(string.sub(data, 1, 100) .. "...")
else
print("Complete response:")
print(data)
end
end

常见响应内容类型

内容类型示例数据用法
application/json{"key":"value"}REST API、现代 Web 服务
text/plainSimple text response状态消息、日志
text/html<html><body>...</body></html>网页、错误页面
application/xml<?xml version="1.0"?><root>...</root>SOAP API、XML 数据
text/csvname,age,city\nJohn,30,NYC数据导出、电子表格

说明

  • 无论原始格式如何,响应数据始终以字符串形式返回
  • 空响应返回空字符串 ""(常见于 204 状态码)
  • 错误响应(4xx、5xx)的响应主体中可能包含有用的错误信息
  • 大型响应可能会占用大量内存 - 如有需要,请考虑分块处理
  • 您可能需要额外的解析库来处理 JSON、XML 或其他结构化格式
  • 在处理之前,请始终检查响应是否为空,以避免错误