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("コメントを作成しました!")
print("レスポンス: " .. data)
else
print("コメントの作成に失敗しました。ステータス: " .. 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("ログイン成功!")
else
print("ログイン失敗。ステータス: " .. status)
end
注記
post()を呼び出す前にsetParameter()を使用してリクエストボディにデータを追加します- POST リクエストには、送信するデータを含むリクエストボディを指定できます
- このメソッドは Response オブジェクトを返し、レスポンスデータとステータスコードにアクセスできます
- リソースの作成が成功した場合、サーバーは通常 201 ステータスコードを返します
- リクエストが成功したかどうかを確認するため、常にレスポンスのステータスコードをチェックしてください
- POST リクエストは冪等ではありません — 同じリクエストを複数回送信すると複数のリソースが作成される可能性があります