Response:getData()
Lấy nội dung thân phản hồi dưới dạng chuỗi từ HTTP response.
Khai báo
getData(): string
Trả về
string - Nội dung thân phản hồi dưới dạng chuỗi
Mô tả
Phương thức getData() lấy nội dung thân phản hồi từ một HTTP response. Nội dung luôn được trả về dưới dạng chuỗi, bất kể định dạng gốc (JSON, XML, văn bản thuần, HTML, v.v.).
Ví dụ
Sử dụng cơ bản
-- Tạo một GET request và lấy dữ liệu phản hồi
local response = Request("https://api.example.com/users"):get()
local userData = response:getData()
print("User data: " .. userData)
Làm việc với dữ liệu JSON
-- Lấy dữ liệu phản hồi JSON
local response = Request("https://api.example.com/posts/1"):get()
local jsonData = response:getData()
-- jsonData sẽ là một chuỗi như: "{\"id\":1,\"title\":\"Sample Post\",\"body\":\"Content\"}"
print("Raw JSON: " .. jsonData)
-- Lưu ý: Bạn sẽ cần một bộ phân tích JSON để chuyển chuỗi này thành Lua table
-- Ví dụ (nếu bạn có bộ phân tích JSON sẵn):
-- local parsedData = json.decode(jsonData)
-- print("Post title: " .. parsedData.title)
Xử lý phản hồi XML
-- Lấy dữ liệu phản hồi XML
local response = Request("https://api.example.com/data.xml"):get()
local xmlData = response:getData()
-- xmlData sẽ chứa nội dung XML dưới dạng chuỗi
if xmlData and xmlData ~= "" then
print("XML data received: " .. xmlData)
-- Bạn sẽ cần một bộ phân tích XML để xử lý dữ liệu này
end
Dữ liệu phản hồi lỗi
-- Tạo một request có thể thất bại
local response = Request("https://api.example.com/invalid"):get()
local statusCode = response:getResponseCode()
if statusCode ~= 200 then
-- Lấy chi tiết lỗi từ thân phản hồi
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
else
print("No error details provided")
end
end
Dữ liệu phản hồi cho POST request
-- Tạo một tài nguyên và lấy phản hồi
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
Xử lý phản hồi rỗng
-- Xử lý các phản hồi có thể rỗng
local response = Request("https://api.example.com/delete/123"):delete()
local status = response:getResponseCode()
local data = response:getData()
if status == 204 then
-- Phản hồi không có nội dung
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
Xử lý các kiểu nội dung khác nhau
-- Kiểm tra header Content-Type nếu có (điều này cần truy cập response headers)
-- Tạm thời, chúng ta có thể phát hiện các mẫu phổ biến trong dữ liệu
local response = Request("https://api.example.com/data"):get()
local data = response:getData()
if data and data ~= "" then
-- Phát hiện định dạng JSON
if string.sub(data, 1, 1) == "{" or string.sub(data, 1, 1) == "[" then
print("Received JSON data")
-- Xử lý như JSON
-- Phát hiện định dạng XML
elseif string.find(data, "^<%?xml") or string.find(data, "^<[^>]+>") then
print("Received XML data")
-- Xử lý như XML
-- Phát hiện định dạng HTML
elseif string.find(data, "^<html") or string.find(data, "^<!DOCTYPE") then
print("Received HTML data")
-- Xử lý như HTML
else
print("Received plain text data")
-- Xử lý như văn bản thuần
end
print("Data length: " .. string.len(data) .. " characters")
else
print("No data received")
end
Xử lý phản hồi lớn
-- Xử lý các phản hồi có thể lớn
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
Các kiểu nội dung phản hồi phổ biến
| Kiểu nội dung | Dữ liệu ví dụ | Cách sử dụng |
|---|---|---|
application/json | {"key":"value"} | REST API, các dịch vụ web hiện đại |
text/plain | Simple text response | Thông báo trạng thái, nhật ký |
text/html | <html><body>...</body></html> | Trang web, trang lỗi |
application/xml | <?xml version="1.0"?><root>...</root> | SOAP API, dữ liệu XML |
text/csv | name,age,city\nJohn,30,NYC Xuất dữ liệu, bảng tính |
Lưu ý
- Dữ liệu phản hồi luôn được trả về dưới dạng chuỗi, bất kể định dạng gốc
- Phản hồi rỗng trả về một chuỗi rỗng
""(thường gặp với mã trạng thái 204) - Phản hồi lỗi (4xx, 5xx) có thể chứa thông tin lỗi hữu ích trong thân phản hồi
- Các phản hồi lớn có thể tiêu tốn đáng kể bộ nhớ - hãy cân nhắc xử lý theo từng phần nếu cần
- Bạn có thể cần các thư viện phân tích cú pháp bổ sung để làm việc với JSON, XML, hoặc các định dạng có cấu trúc khác
- Luôn kiểm tra xem phản hồi có rỗng trước khi xử lý để tránh lỗi