Request():post()
Thực thi một yêu cầu POST và trả về một đối tượng Response. Phương thức này được dùng để gửi dữ liệu đến máy chủ, thường là để tạo một tài nguyên mới.
Khai báo
post(): Response
Trả về
Response - Đối tượng phản hồi chứa kết quả từ máy chủ
Mô tả
Phương thức post() gửi một yêu cầu HTTP POST đến URL được chỉ định khi tạo đối tượng Request. Yêu cầu POST thường được dùng để gửi dữ liệu lên máy chủ để xử lý, chẳng hạn như tạo bản ghi mới, gửi biểu mẫu hoặc tải dữ liệu lên.
Sử dụng setParameter() để thêm dữ liệu vào phần thân yêu cầu (request body) trước khi gọi post().
Ví dụ
Yêu cầu POST cơ bản
-- Tạo một yêu cầu POST với các tham số
local response = Request("https://api.example.com/users")
:setParameter("name", "John Doe")
:setParameter("email", "john@example.com")
:post()
Yêu cầu POST với JSON Headers
-- Yêu cầu POST với kiểu nội dung JSON
local response = Request("https://api.example.com/posts")
:setHeader("Content-Type", "application/json")
:setHeader("Authorization", "Bearer your-token-here")
:setParameter("title", "My New Post")
:setParameter("body", "This is the content of my post")
:setParameter("userId", "1")
:post()
Xử lý phản hồi POST
-- Thực hiện yêu cầu POST và xử lý phản hồi
local response = Request("https://api.example.com/comments")
:setHeader("Content-Type", "application/json")
:setParameter("postId", "1")
:setParameter("name", "Anonymous User")
:setParameter("email", "user@example.com")
:setParameter("body", "Great article!")
:post()
-- Lấy dữ liệu phản hồi
local data = response:getData()
local statusCode = response:getResponseCode()
if statusCode == 201 then
print("Bình luận đã được tạo thành công!")
print("Phản hồi: " .. data)
else
print("Tạo bình luận thất bại. Mã trạng thái: " .. statusCode)
end
Gửi biểu mẫu với POST
-- Giả lập việc gửi biểu mẫu
local response = Request("https://example.com/login")
:setHeader("Content-Type", "application/x-www-form-urlencoded")
:setParameter("username", "myusername")
:setParameter("password", "mypassword")
:setParameter("remember", "true")
:post()
local loginResponse = response:getData()
local status = response:getResponseCode()
if status == 200 then
print("Đăng nhập thành công!")
else
print("Đăng nhập thất bại. Mã trạng thái: " .. status)
end
Lưu ý
- Sử dụng
setParameter()để thêm dữ liệu vào phần thân yêu cầu trước khi gọipost() - Yêu cầu POST có thể có phần thân (request body) chứa dữ liệu cần gửi
- Phương thức trả về một đối tượng Response mà bạn có thể dùng để truy cập dữ liệu phản hồi và mã trạng thái
- Khi tạo tài nguyên thành công, máy chủ thường trả về mã trạng thái 201
- Luôn kiểm tra mã trạng thái phản hồi để đảm bảo yêu cầu đã thành công
- Yêu cầu POST không idempotent - việc thực hiện cùng một yêu cầu nhiều lần có thể tạo ra nhiều tài nguyên