إنتقل إلى المحتوى الرئيسي

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، خدمات الويب الحديثة
text/plainSimple text responseرسائل الحالة، السجلات
text/html<html><body>...</body></html>صفحات الويب، صفحات الأخطاء
application/xml<?xml version="1.0"?><root>...</root>واجهات SOAP، بيانات XML
text/csvname,age,city\nJohn,30,NYCتصدير البيانات، جداول البيانات

ملاحظات

  • تُعاد بيانات الاستجابة دائمًا كسلسلة نصية، بصرف النظر عن التنسيق الأصلي
  • الاستجابات الفارغة تُعيد سلسلة فارغة "" (شائع مع رموز الحالة 204)
  • استجابات الخطأ (4xx أو 5xx) قد تحتوي على معلومات خطأ مفيدة في متن الاستجابة
  • الاستجابات الكبيرة قد تستهلك ذاكرة كبيرة - فكر في المعالجة على أجزاء عند الحاجة
  • قد تحتاج إلى مكتبات تحليل إضافية للعمل مع JSON أو XML أو غيرها من التنسيقات المهيكلة
  • تحقق دائمًا مما إذا كانت الاستجابة فارغة قبل المعالجة لتجنب الأخطاء