본문으로 건너뛰기

Response:getData()

HTTP 응답에서 응답 본문 콘텐츠를 문자열로 가져옵니다.

시그니처

getData(): string

반환값

string - 응답 본문 콘텐츠를 문자열로 반환

설명

getData() 메서드는 HTTP 응답에서 응답 본문 콘텐츠를 가져옵니다. 이 콘텐츠는 원래 형식(JSON, XML, 일반 텍스트, HTML 등)과 관계없이 항상 문자열로 반환됩니다.

예시

기본 사용

-- GET 요청을 수행하고 응답 데이터를 가져옵니다
local response = Request("https://api.example.com/users"):get()
local userData = response:getData()
print("User data: " .. userData)

JSON 데이터 다루기

-- JSON 응답 데이터를 가져옵니다
local response = Request("https://api.example.com/posts/1"):get()
local jsonData = response:getData()

-- jsonData는 "{\"id\":1,\"title\":\"Sample Post\",\"body\":\"Content\"}"와 같은 문자열입니다
print("Raw JSON: " .. jsonData)

-- 참고: 이 문자열을 Lua 테이블로 변환하려면 JSON 파서가 필요합니다
-- 예시 (JSON 파서를 사용할 수 있는 경우):
-- local parsedData = json.decode(jsonData)
-- print("Post title: " .. parsedData.title)

XML 응답 처리

-- XML 응답 데이터를 가져옵니다
local response = Request("https://api.example.com/data.xml"):get()
local xmlData = response:getData()

-- xmlData는 XML 콘텐츠를 문자열로 포함합니다
if xmlData and xmlData ~= "" then
print("XML data received: " .. xmlData)
-- 이 데이터를 처리하려면 XML 파서가 필요합니다
end

에러 응답 데이터

-- 실패할 수 있는 요청을 수행합니다
local response = Request("https://api.example.com/invalid"):get()
local statusCode = response:getResponseCode()

if statusCode ~= 200 then
-- 응답 본문에서 에러 상세 정보를 가져옵니다
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
else
print("No error details provided")
end
end

POST 요청 응답 데이터

-- 리소스를 생성하고 응답을 가져옵니다
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

빈 응답 처리

-- 비어 있을 수 있는 응답을 처리합니다
local response = Request("https://api.example.com/delete/123"):delete()
local status = response:getResponseCode()
local data = response:getData()

if status == 204 then
-- 콘텐츠 없음 응답
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

다양한 콘텐츠 유형 처리

-- 가능한 경우 Content-Type 헤더를 확인합니다 (응답 헤더에 접근해야 함)
-- 지금은 데이터에서 일반적인 패턴을 감지할 수 있습니다
local response = Request("https://api.example.com/data"):get()
local data = response:getData()

if data and data ~= "" then
-- JSON 형식 감지
if string.sub(data, 1, 1) == "{" or string.sub(data, 1, 1) == "[" then
print("Received JSON data")
-- JSON으로 처리
-- XML 형식 감지
elseif string.find(data, "^<%?xml") or string.find(data, "^<[^>]+>") then
print("Received XML data")
-- XML로 처리
-- HTML 형식 감지
elseif string.find(data, "^<html") or string.find(data, "^<!DOCTYPE") then
print("Received HTML data")
-- HTML로 처리
else
print("Received plain text data")
-- 일반 텍스트로 처리
end

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

대용량 응답 처리

-- 잠재적으로 큰 응답을 처리합니다
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, 최신 웹 서비스
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 또는 기타 구조화된 형식을 다루려면 추가 파싱 라이브러리가 필요할 수 있습니다.
  • 에러를 방지하려면 처리하기 전에 항상 응답이 비어 있는지 확인하세요.