跳到主要内容

Request():post()

执行 POST 请求并返回一个 Response 对象。此方法用于向服务器发送数据,通常用于创建新资源。

签名

post(): Response

返回值

Response - 包含服务器响应的响应对象

描述

post() 方法向创建 Request 对象时指定的 URL 发送 HTTP POST 请求。POST 请求通常用于向服务器提交数据以进行处理,例如创建新记录、提交表单或上传数据。

在调用 post() 之前,请使用 setParameter() 向请求体添加数据。

示例

基本 POST 请求

-- 带参数的 POST 请求
local response = Request("https://api.example.com/users")
:setParameter("name", "John Doe")
:setParameter("email", "john@example.com")
:post()

带 JSON 请求头的 POST 请求

--JSON 内容类型的 POST 请求
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()

处理 POST 响应

-- 发起 POST 请求并处理响应
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()

-- 获取响应数据
local data = response:getData()
local statusCode = response:getResponseCode()

if statusCode == 201 then
print("Comment created successfully!")
print("Response: " .. data)
else
print("Failed to create comment. Status: " .. statusCode)
end

使用 POST 提交表单

-- 模拟表单提交
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("Login successful!")
else
print("Login failed. Status: " .. status)
end

说明

  • 在调用 post() 之前,请使用 setParameter() 向请求体添加数据
  • POST 请求可以包含请求体,其中存放要发送的数据
  • 该方法返回一个 Response 对象,您可以通过它访问响应数据和状态码
  • 资源创建成功时,服务器通常返回 201 状态码
  • 请始终检查响应状态码,以确保请求成功
  • POST 请求不是幂等的——多次发起相同的请求可能会创建多个资源