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、モダンな Web サービス |
text/plain | Simple text response | ステータスメッセージ、ログ |
text/html | <html><body>...</body></html> | Web ページ、エラーページ |
application/xml | <?xml version="1.0"?><root>...</root> | SOAP API、XML データ |
text/csv | name,age,city\nJohn,30,NYC | データエクスポート、スプレッドシート |
注記
- レスポンスデータは、元の形式に関わらず常に文字列として返されます
- 空のレスポンスは空文字列
""を返します(204 ステータスコードでよく見られます) - エラーレスポンス(4xx、5xx)には、レスポンスボディに有用なエラー情報が含まれている場合があります
- 大きなレスポンスはメモリを多く消費する可能性があります。必要に応じてチャンク単位で処理を検討してください
- JSON、XML、その他の構造化フォーマットを処理するには、追加のパースライブラリが必要な場合があります
- エラーを防ぐため、処理前に必ずレスポンスが空かどうかを確認してください