HttpService
*このコンテンツは、ベータ版のAI(人工知能)を使用して翻訳されており、エラーが含まれている可能性があります。このページを英語で表示するには、 こちら をクリックしてください。
HttpService は、RequestAsync、GetAsync、PostAsync を使用してゲームサーバーから HTTP リクエストを送信できます。このサービスでは、ゲームがアナリティクス、データストレージ、リモートサーバー構成、エラー報告、高度な解析算、またはリアルタイムコミュニケーションなどのオフ Roblox ウェブサービスと統合できます。
HttpService には、JSONEncode および JSONDecode 方法も含まれており、JSON 形式を使用するサービスとの通信に便利な方法も含まれています。さらに、GenerateGUID メソッドは、ランダムな 128ビットラベルを提供し、さまざまなシナリオで確率的に唯一として扱うことができます。
エクスペリエンスをセキュリティリスクにさらすことを避けるために、信頼できる第三者プラットフォームにのみ HTTP リクエストを送信する必要があります。
このプロパティは、実行時にインタラクトできません。
HTTP リクエストを有効にする
リクエスト送信方法はデフォルトで有効になっていません。リクエストを送信するには、エクスペリエンスのために HTTP リクエストを有効にする 必要があります。
プラグインで使用
HttpService は、Studio プラグインで使用できます。アップデートをチェックしたり、使用データを送信したり、コンテンツをダウンロードしたり、他のビジネスロジックを実行するためにこれを行う可能性があります。プラグインがこれを行おうとする最初の時に、ユーザーに特定のウェブアドレスと通信する権限をプラグインに与えるよう求められる可能性があります。ユーザーは、 プラグイン管理 ウィンドウを通じて、いつでもそのような権限を承認、拒否、撤回できます。
プラグインは、localhost および 127.0.0.1 ホストを介して、同じコンピュータ上で実行中の他のソフトウェアとも通信できます。このプラグインと互換性のあるプログラムを実行することで、プラグインの機能を通常の Studio 機能以上に拡張できます、例えばコンピュータのファイルシステムとの対話などそのようなソフトウェアは、プラグイン自体とは別に配布されなければならず、注意しなければセキュリティ上の脅威になる可能性があります。
追加の注意事項
- ポート制限があります。ポート 1194 または 1024 以下のポートを使用できません、除き 80 と 443 のみ。ブロックされたポートを使おうとすると、403 Forbidden または ERR_ACCESS_DENIED エラーが発生します。
- Roblox ゲームサーバーごとに、分ごとに 500 HTTP リクエストの制限があります。これを超えると、リクエスト送信方法が約 30秒間完全に停止する可能性があります。
- www.roblox.comなどの Roblox ウェブサイトにリクエストを送信することはできません。
- Web リクエストは多くの理由で失敗する可能性があるため、「防御的にコードを使用」(pcall())し、リクエストが失敗したときのプランを持つことが重要です。
- http:// プロトコルはサポートされていますが、可能な限り https:// を使用する必要があります。
- 送信されたリクエストは、プリシェアされた秘密鍵などの安全な認証形キーを提供して、悪意のあるアクターが Roblox ゲームサーバーの 1つとして偽装できないようにする必要があります。
- リクエストが送信されるウェブサーバーの一般的な容量とレート制限政策を認識してください。
コードサンプル
This code sample uses HttpService's GetAsync to make a request to Open Notify, a web service that provides data from NASA. The request is made to an endpoint that provides information on how many astronauts are currently in space. The response is provided in JSON format, so it is parsed using JSONDecode. Finally, the response data is then processed and printed to the Output.
Test this script by pasting the source code into a Script (HttpService cannot be used by LocalScripts). Also, be sure to enable HTTP Requests in your Game Settings (Home > Game Settings).
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Make the request to our endpoint URL
local response = HttpService:GetAsync(URL_ASTROS)
-- Parse the JSON response
local data = HttpService:JSONDecode(response)
-- Information in the data table is dependent on the response JSON
if data.message == "success" then
print("There are currently " .. data.number .. " astronauts in space:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " is on " .. person.craft)
end
end
This code sample uses HttpService's GetAsync to make a request to an endpoint at Open Notify, a website that provides information from NASA. The endpoint provides information on the current location of the International Space Station. This example uses a defensive coding technique that you should use when making web requests. It wraps the call to GetAsync and JSONDecode in pcall, which protects our script from raising an error if either of these fail. Then, it checks the raw response for all proper data before using it. All of this is put inside a function that returns true or false depending of the request's success.
Whenever you're working with web requests, you should prepare for anything to go wrong. Perhaps your web endpoint changes or goes down - you don't want your game scripts raising errors and breaking your game. You want to handle both success and failure gracefully - have a plan in case your data is not available. Use pcall and make plenty of validity checks (if statements) on your data to make sure you're getting exactly what you expect.
local HttpService = game:GetService("HttpService")
-- Where is the International Space Station right now?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- Use pcall in case something goes wrong
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- Did our request fail or our JSON fail to parse?
if not data then
return false
end
-- Fully check our data for validity. This is dependent on what endpoint you're
-- to which you're sending your requests. For this example, this endpoint is
-- described here: http://open-notify.org/Open-Notify-API/ISS-Location-Now/
if data.message == "success" and data.iss_position then
if data.iss_position.latitude and data.iss_position.longitude then
print("The International Space Station is currently at:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("Success")
else
print("Something went wrong")
end
Pastebin.com is a website that allows users to paste text (usually source code) for others to view publicly. This code sample uses HttpService PostAsync and the pastebin web API to automatically create a new public paste on the website. Since pastebin's API is designed to take data in as a URL encoded string, the code uses a for-loop to turn the dataFields table into a URL encoded string, such as hello=world&foo=bar. This is used as the HTTP POST data.
Test this code by first going to pastebin.com/api#1 and getting an API key (you'll need a pastebin account to do this). Then, paste your unique developer API key into the field api_dev_key in the code sample's dataFields table. Fill in any other information about the post you want to make, then run this code in a Script (not a LocalScript). If all goes well, you'll get a URL to your new paste in the Output window (or some error string from pastebin).
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API developer key from
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- keep as "paste"
["api_paste_name"] = "HttpService:PostAsync", -- paste name
["api_paste_code"] = "Hello, world", -- paste content
["api_paste_format"] = "text", -- paste format
["api_paste_expire_date"] = "10M", -- expire date
["api_paste_private"] = "0", -- 0=public, 1=unlisted, 2=private
["api_user_key"] = "", -- user key, if blank post as guest
}
-- The pastebin API uses a URL encoded string for post data
-- Other APIs might use JSON, XML or some other format
local data = ""
for k, v in pairs(dataFields) do
data = data .. ("&%s=%s"):format(HttpService:UrlEncode(k), HttpService:UrlEncode(v))
end
data = data:sub(2) -- Remove the first &
-- Here's the data we're sending
print(data)
-- Make the request
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- The response will be the URL to the new paste (or an error string if something was wrong)
print(response)
概要
プロパティ
HTTP リクエストを外部のウェブサイトに送信できるかどうかを示します。
方法
UUID/GUID ランダムな文字列を生成し、オプションでカーリーブレースを使用します。
シークレットストアから Secret を返します。
JSON 文字列を Luau テーブルにデコードします。
Luau テーブルから JSON ストリングを生成します。
URL-安全でない文字を「%」と 2 十六進コードで置換します。
HTTP GET リクエストを送信します。
- PostAsync(url : Variant,data : string,content_type : Enum.HttpContentType,compress : boolean,headers : Variant):string
HTTP POST リクエストを送信します。
情報の辞書を指定された HTTP メソッドを使用して HTTP リクエストを送信します。
プロパティ
HttpEnabled
true に設定すると、スクリプトが HttpService:GetAsync()、HttpService:PostAsync()、および HttpService:RequestAsync() を使用してウェブサイトにリクエストを送信できます。
このプロパティは、Studio の ゲーム設定 インターフェイスを介して切り替えるか、 公開されていない 経験でこのプロパティを true に設定して コマンドバー を使用して切り替える必要があります:
game:GetService("HttpService").HttpEnabled = true
方法
GenerateGUID
このメソッドは、 ランダムなユニバーサルユニーク識別子 (UUID) の文字列を生成します。UID の十六バイトは、ハイフンで区切られた 5 グループに表示され、合計 36 文字の形式で 8-4-4-4-12 に表示され、例えば 123e4567-e89b-12d3-a456-426655440000 です。
使用されているUID 仕様は バージョン 4 (ランダム)、バージョン 1 (DCE 1.1、ISO/IEC 11578:1996)です。このバージョンの UUID は、完全にランダムに生成されるため、単純さのために最もよく使用されます。このバージョンには、他のUUID バージョンにある特定の機能がありません、例えば、エンコードされたタイムスタンプ、MAC アドレス、または時間ベースのソートのように UUIDv7 または ULID のようなもの。
5.3×10 36 のユニークな v4 UUIDには、103兆の UUID 内で複製を見つける確率が 1億分の 1 になるユニークな UUIDがあります。
wrapInCurlyBraces 引数は、返された文字列がカーリーブレースで包まれているかどうかを決定します ({} )。たとえインスタンス:
- true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
- false : db454790-7563-44ed-ab4b-397ff5df737b
パラメータ
返された文字列がカーリーブレースで包まれるべきかどうか ( {} )。
戻り値
ランダムに生成されたUID。
コードサンプル
This example uses HttpService's GenerateGUID method to generate and print a universally unique identifier.
local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}
GetSecret
このメソッドは、エクスペリエンスのために以前にシークレットストアに追加された値を返します。秘密のコンテンツはプリントアウトできず、エクスペリエンスがローカルで実行されると利用できません。
返された Secret は、Secret:AddPrefix() などの組み込みメソッドを使用して変換できます。HTTP リクエストの一部として送信されることが期待されます。
詳しくは、使用ガイド を参照してください。
パラメータ
戻り値
JSONDecode
このメソッドは、JSON オブジェクトまたはアレイを次の特徴で Luau テーブル に変換します:
- テーブルのキーは文字列または数字ですが、両方はありません。JSON オブジェクトに両方含まれている場合、文字列キーは無視されます。
- 空の JSON オブジェクトは空の Luau テーブルを生成します ({} )。
- input 文字列が有効な JSON オブジェクトでない場合、このメソッドはエラーをスローします。
Luau テーブルを JSON オブジェクトにエンコードするには、HttpService:JSONEncode() メソッドを使用します。
このメソッドは、HTTP リクエストが有効になっているかどうかに関わらず使用できます。
パラメータ
JSON オブジェクトがデコードされています。
戻り値
JSON オブジェクトを Luau テーブルとしてデコードしました。
コードサンプル
This code sample gives an example JSON format string and parses it using HttpService's JSONDecode. It then verifies that the JSON was parsed correctly, and prints out some of the information within the object.
Try editing the JSON string to experiment with the format. Also experiment with inspecting the data in Lua to get comfortable with the Lua representation of the data (tables and other values).
local HttpService = game:GetService("HttpService")
local jsonString = [[
{
"message": "success",
"info": {
"points": 120,
"isLeader": true,
"user": {
"id": 12345,
"name": "JohnDoe"
},
"past_scores": [50, 42, 95],
"best_friend": null
}
}
]]
local data = HttpService:JSONDecode(jsonString)
if data.message == "success" then
-- Since tab["hello"] and tab.hello are equivalent,
-- you could also use data["info"]["points"] here:
print("I have " .. data.info.points .. " points")
if data.info.isLeader then
print("I am the leader")
end
print("I have " .. #data.info.past_scores .. " past scores")
print("All the information:")
for key, value in pairs(data.info) do
print(key, typeof(value), value)
end
end
JSONEncode
このメソッドは、Luau テーブル を次のガイドラインに基づいて JSON オブジェクトまたは配列に変換します:
テーブルのキーは文字列または数字である必要があります。如果テーブルに両方含まれている場合、配列が優先されます (文字列のキーは無視されます)。
空の Luau テーブル ( {} ) は、空の JSON 配列を生成します。
値 nil は決して生成されません。
サイクルテーブル参照はエラーを引き起こします。
このメソッドは、無効な JSON のような値 inf や nan を許可します。これは、他の場所で出力された JSON を使用したい場合に問題を引き起こす可能性があります。
エンコードプロセスを逆にして JSON オブジェクトをデコードするには、HttpService:JSONDecode() メソッドを使用します。
このメソッドは、HTTP リクエストが有効になっているかどうかに関わらず使用できます。
パラメータ
入力 Luau テーブル。
戻り値
返された JSON 文字列。
コードサンプル
This code sample turns a Lua table tab into a JSON string using HttpService's JSONEncode. Then, it prints out the string.
Try editing the Lua table to see how the JSON output changes.
local HttpService = game:GetService("HttpService")
local tab = {
-- Remember: these lines are equivalent
--["message"] = "success",
message = "success",
info = {
points = 123,
isLeader = true,
user = {
id = 12345,
name = "JohnDoe",
},
past_scores = { 50, 42, 95 },
best_friend = nil,
},
}
local json = HttpService:JSONEncode(tab)
print(json)
UrlEncode
このメソッドは、パーセントコード を使用して、指定の文字列を と 2 十六進コードで正しく符号化し、予約文字が で正しく符号化されるようにします。
これは、HttpService:GetAsync() / HttpService:PostAsync() 、または POST メディアタイプのデータ application/x-www-form-urlencoded (Enum.HttpContentType.ApplicationUrlEncoded) を使用するときに URL を形式化するのに便利です。
たとえば、URLをエンコードして https://www.roblox.com/discover#/ 、このメソッドは https%3A%2F%2Fwww%2Eroblox%2Ecom%2Fdiscover%23%2F を返します。
パラメータ
エンコードする文字列 (URL)。
戻り値
エンコードされた文字列。
コードサンプル
This code sample uses UrlEncode to turn a string into a safe, percent-encoded string that can be used in a URL as an argument. Notice how only unreserved characters (letters, numbers and -_.~) are not transformed into percent-encoded equivalents. Characters with accents are also transformed (for example é is transformed into %C3).
local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- French for "I went to the movies"
local result = HttpService:UrlEncode(content)
print(result) --> Je%20suis%20all%C3%A9%20au%20cinema%2E
Pastebin.com is a website that allows users to paste text (usually source code) for others to view publicly. This code sample uses HttpService PostAsync and the pastebin web API to automatically create a new public paste on the website. Since pastebin's API is designed to take data in as a URL encoded string, the code uses a for-loop to turn the dataFields table into a URL encoded string, such as hello=world&foo=bar. This is used as the HTTP POST data.
Test this code by first going to pastebin.com/api#1 and getting an API key (you'll need a pastebin account to do this). Then, paste your unique developer API key into the field api_dev_key in the code sample's dataFields table. Fill in any other information about the post you want to make, then run this code in a Script (not a LocalScript). If all goes well, you'll get a URL to your new paste in the Output window (or some error string from pastebin).
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API developer key from
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- keep as "paste"
["api_paste_name"] = "HttpService:PostAsync", -- paste name
["api_paste_code"] = "Hello, world", -- paste content
["api_paste_format"] = "text", -- paste format
["api_paste_expire_date"] = "10M", -- expire date
["api_paste_private"] = "0", -- 0=public, 1=unlisted, 2=private
["api_user_key"] = "", -- user key, if blank post as guest
}
-- The pastebin API uses a URL encoded string for post data
-- Other APIs might use JSON, XML or some other format
local data = ""
for k, v in pairs(dataFields) do
data = data .. ("&%s=%s"):format(HttpService:UrlEncode(k), HttpService:UrlEncode(v))
end
data = data:sub(2) -- Remove the first &
-- Here's the data we're sending
print(data)
-- Make the request
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- The response will be the URL to the new paste (or an error string if something was wrong)
print(response)
GetAsync
このメソッドは HTTP GET リクエストを送信します。HTTP リクエストパラメータを単一の辞書ではなく、メソッドパラメータとして受け入れ、HTTP 応答の体だけを返すことを除いて、RequestAsync() と同様に機能します。一般的に、このメソッドは短縮形としてのみ有用であり、RequestAsync() はほとんどの場合に使用する必要があります。
When true , the nocache パラメータは、このメソッドが同じ url で前の呼び出しの結果をキャッシュするのを防ぎます。
パラメータ
データをリクエストしているウェブアドレス。
リクエストが応答を保存するかどうか。
一部の HTTP リクエストヘッダを指定するために使用されます。
戻り値
GET リクエストの応答ボディ。
コードサンプル
This code sample uses HttpService's GetAsync to make a request to Open Notify, a web service that provides data from NASA. The request is made to an endpoint that provides information on how many astronauts are currently in space. The response is provided in JSON format, so it is parsed using JSONDecode. Finally, the response data is then processed and printed to the Output.
Test this script by pasting the source code into a Script (HttpService cannot be used by LocalScripts). Also, be sure to enable HTTP Requests in your Game Settings (Home > Game Settings).
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Make the request to our endpoint URL
local response = HttpService:GetAsync(URL_ASTROS)
-- Parse the JSON response
local data = HttpService:JSONDecode(response)
-- Information in the data table is dependent on the response JSON
if data.message == "success" then
print("There are currently " .. data.number .. " astronauts in space:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " is on " .. person.craft)
end
end
This code sample uses HttpService's GetAsync to make a request to an endpoint at Open Notify, a website that provides information from NASA. The endpoint provides information on the current location of the International Space Station. This example uses a defensive coding technique that you should use when making web requests. It wraps the call to GetAsync and JSONDecode in pcall, which protects our script from raising an error if either of these fail. Then, it checks the raw response for all proper data before using it. All of this is put inside a function that returns true or false depending of the request's success.
Whenever you're working with web requests, you should prepare for anything to go wrong. Perhaps your web endpoint changes or goes down - you don't want your game scripts raising errors and breaking your game. You want to handle both success and failure gracefully - have a plan in case your data is not available. Use pcall and make plenty of validity checks (if statements) on your data to make sure you're getting exactly what you expect.
local HttpService = game:GetService("HttpService")
-- Where is the International Space Station right now?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- Use pcall in case something goes wrong
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- Did our request fail or our JSON fail to parse?
if not data then
return false
end
-- Fully check our data for validity. This is dependent on what endpoint you're
-- to which you're sending your requests. For this example, this endpoint is
-- described here: http://open-notify.org/Open-Notify-API/ISS-Location-Now/
if data.message == "success" and data.iss_position then
if data.iss_position.latitude and data.iss_position.longitude then
print("The International Space Station is currently at:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("Success")
else
print("Something went wrong")
end
PostAsync
このメソッドは HTTP POST リクエストを送信します。HTTP リクエストパラメータを単一の辞書ではなく、メソッドパラメータとして受け入れ、HTTP 応答の体だけを返すことを除いて、RequestAsync() と同様に機能します。一般的に、このメソッドは短縮形としてのみ有用であり、RequestAsync() はほとんどの場合に使用する必要があります。
When true , the compress パラメータは、大きなリクエストボディが gzip を使用して圧縮されるかどうかを制御します。
パラメータ
データの目的地アドレス。
送信されるデータ。
リクエストで送信された Content-Type ヘッダーの値を変更します。
データが送信されるときに圧縮されるかどうかを決定します( gzipped )行
一部の HTTP リクエストヘッダを指定するために使用されます。
戻り値
リクエスト結果を示す HTTP 返答。
コードサンプル
Pastebin.com is a website that allows users to paste text (usually source code) for others to view publicly. This code sample uses HttpService PostAsync and the pastebin web API to automatically create a new public paste on the website. Since pastebin's API is designed to take data in as a URL encoded string, the code uses a for-loop to turn the dataFields table into a URL encoded string, such as hello=world&foo=bar. This is used as the HTTP POST data.
Test this code by first going to pastebin.com/api#1 and getting an API key (you'll need a pastebin account to do this). Then, paste your unique developer API key into the field api_dev_key in the code sample's dataFields table. Fill in any other information about the post you want to make, then run this code in a Script (not a LocalScript). If all goes well, you'll get a URL to your new paste in the Output window (or some error string from pastebin).
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API developer key from
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- keep as "paste"
["api_paste_name"] = "HttpService:PostAsync", -- paste name
["api_paste_code"] = "Hello, world", -- paste content
["api_paste_format"] = "text", -- paste format
["api_paste_expire_date"] = "10M", -- expire date
["api_paste_private"] = "0", -- 0=public, 1=unlisted, 2=private
["api_user_key"] = "", -- user key, if blank post as guest
}
-- The pastebin API uses a URL encoded string for post data
-- Other APIs might use JSON, XML or some other format
local data = ""
for k, v in pairs(dataFields) do
data = data .. ("&%s=%s"):format(HttpService:UrlEncode(k), HttpService:UrlEncode(v))
end
data = data:sub(2) -- Remove the first &
-- Here's the data we're sending
print(data)
-- Make the request
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- The response will be the URL to the new paste (or an error string if something was wrong)
print(response)
RequestAsync
このメソッドは、辞書を使用して HTTP リクエストを送信し、ターゲット URL、メソッド、ヘッダー、リクエストボディデータなどのリクエストデータを指定します。受信した応答データを記述する辞書を返します。オプションで、リクエストは Enum.HttpCompression を使用して圧縮できます。
辞書フィールドをリクエスト
<th>種類</th><th>必要</th><th>説明</th></tr></thead><tbody><tr><td><code>Url</code></td><td>ストリング</td><td>はい</td><td>このリクエストのターゲット URL。<code>http</code> または <code>https</code> プロトコルを使用する必要があります。</td></tr><tr><td><code>手法</code></td><td>ストリング</td><td>no</td><td>このリクエストで使用されている HTTP メソッドは、ほとんどが <code>取得</code> または <code>ポスト</code> です。</td></tr><tr><td><code>ヘッダ</code></td><td>辞書</td><td>no</td><td>このリクエストで使用するヘッダの辞書。ほとんどの HTTP ヘッダはここで受け入れられますが、すべてではありません。</td></tr><tr><td><code>体</code></td><td>ストリング</td><td>no</td><td>リクエストボディ。バイナリデータを含む任意の文字列が使用できます。<code>GET</code> または <code>HEAD</code> HTTP メソッドを使用するときは除外する必要があります。JSON または他の形式を送信するときに <code>コンテントタイプ</code> ヘッダーを指定する必要があるかもしれません。</td></tr><tr><td><code>圧縮</code></td><td><code>Enum.HttpCompression</code></td><td>no</td><td>リクエストのデータを圧縮するオプションの圧縮フィールド。値は <code>Enum.HttpCompression.None</code> または <code>Enum.HttpCompression.Gzip</code> であることができます。</td></tr></tbody>
名前 |
---|
HTTP メソッドをサポート
HTTP リクエストメソッドは、リクエストが行われる目的と、リクエストが成功した場合の期待される内容を指定します。たとえば、GET リクエストメソッドは、リクエストされたアドレスに資源が要求されていることをサーバーに通知し、成功すると、そのアドレスの資源が返されます。同様に、HEAD リクエストメソッドも、サーバーが Body 要素なしで応答を返すことを知っているのを除き、同じことを行います。
<th>説明</th><th>安全</th></tr></thead><tbody><tr><td><code>取得</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/GET">ⓘ</a></td><td><code>GET</code> メソッドは、指定されたアドレスでリソースをリクエストします。<code>ボディ</code> パラメータの使用はサポートしません。</td><td>はい</td></tr><tr><td><code>頭</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/HEAD">ⓘ</a></td><td><code>頭</code> メソッドは、<code>取得</code> リクエストと同じ応答を要求しますが、応答体はありません。<code>ボディ</code> パラメータの使用をサポートしていません。</td><td>はい</td></tr><tr><td><code>ポスト</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/POST">ⓘ</a></td><td><code>POST</code> メソッドは、提供された <code>ボディ</code> データを指定されたアドレスに送信します。</td><td>No</td></tr><tr><td><code>PUT</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PUT">ⓘ</a></td><td><code>PUT</code> メソッドは、供与された <code>ボディ</code> データ内で指定された資源のすべての現在の反復を置き換えます。</td><td>No</td></tr><tr><td><code>削除</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/DELETE">ⓘ</a></td><td><code>削除</code> メソッドは、指定された <code>ボディ</code> データに含まれる資源を、指定されたアドレスで削除します。</td><td>No</td></tr><tr><td><code>オプション</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/OPTIONS">ⓘ</a></td><td><code>オプション</code> メソッドは、指定されたアドレスの許可された通信オプションをリクエストします。</td><td>はい</td></tr><tr><td><code>トレース</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/TRACE">ⓘ</a></td><td><code>トレース</code> メソッドは、提供された <code>ボディ</code> データに指定されたリソースへのパスを通してメッセージループバックテストを実行します。</td><td>はい</td></tr><tr><td><code>パッチ</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PATCH">ⓘ</a></td><td><code>パッチ</code> メソッドは、指定された <code>ボディ</code> データで指定されたリソースに部分的な変更を適用します。要求されたアドレスに。</td><td>No</td></tr></tbody>
手法 |
---|
HTTP ヘッダ
リクエスト辞書では、リクエストで使用するカスタム HTTP ヘッダーを指定できます。しかし、いくつかのヘッダーは指定できません。たとえば、Content-Length はリクエストボディから決定されます。User-Agent と Roblox-Id は Roblox によってロックされています。Accept または Cache-Control のような他のヘッダーは、デフォルト値を使用しますが、オーバーライドできます。より一般的に、一部の REST API は、リクエストヘッダーに API キーまたは他のサービスの認証が指定される必要があります。
RequestAsync() メソッドは、ボディコンテンツの形式を検出しません。多くのウェブサーバーは、特定の形式を送信するときに Content-Type ヘッダーが適切に設定される必要があります。他のメソッドの 使用は、 枚列を使用します;このメソッドでは、 ヘッダーを適切に設定します: 、 、 、 または は、それぞれの枚列の値に対する置換ヘッダー値です。
応答辞書フィールド
RequestAsync() は、次のフィールドを含む辞書を返します:
<th>種類</th><th>説明</th></tr></thead><tbody><tr><td><code>成功</code></td><td>ブールブルーン</td><td>リクエストの成功状況。これは、<code>ステータスコード</code> が範囲 <code>200</code> - <code>299</code> 内にある場合にのみ真です。</td></tr><tr><td><code>ステータスコード</code></td><td>整数</td><td>応答のステータスを識別する HTTP 応答コード。</td></tr><tr><td><code>ステータスメッセージ</code></td><td>ストリング</td><td>返送されたステータスメッセージ。</td></tr><tr><td><code>ヘッダ</code></td><td>辞書</td><td>この応答で設定されたヘッダの辞書。</td></tr><tr><td><code>体</code></td><td /><td>応答で受信されたリクエストボディ (コンテンツ)</td></tr></tbody>
名前 |
---|
エラーケース
RequestAsync() 応答が期限切れになるか、ターゲットサーバーがリクエストを拒否するとエラーが発生します。Web サービスが何らかの理由でダウンすると、このメソッドを使用するスクリプトが全く機能しなくなる可能性があります。このメソッドへの呼び出しを pcall() で包んで、必要な情報がない場合に優雅に失敗ケースを処理するのがよいアイデアです。
制限
現在の HTTP リクエストの送信と受信の制限は、分ごとに 500 リクエストです。この境界を超えたリクエストは失敗します。さらに、Roblox ドメインは除外されます。これは、www.roblox.com のような Roblox が所有するサイトに HTTP リクエストを送信できないことを意味します。
パラメータ
サーバーにリクエストする情報を含む辞書。指定されたサーバーから要求される。
戻り値
サーバーが指定された応答情報を含む辞書。
コードサンプル
This code sample demonstrates sending a single HTTP POST request with JSON data to the website httpbin.org, a website that helps debug HTTP requests. Here, we send some JSON data by using HttpService:JSONEncode() and also setting the Content-Type header.
-- Remember to set enable HTTP Requests in game settings!
local HttpService = game:GetService("HttpService")
local function request()
local response = HttpService:RequestAsync({
Url = "http://httpbin.org/post", -- This website helps debug HTTP requests
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- When sending JSON, set this!
},
Body = HttpService:JSONEncode({ hello = "world" }),
})
if response.Success then
print("Status code:", response.StatusCode, response.StatusMessage)
print("Response body:\n", response.Body)
else
print("The request failed:", response.StatusCode, response.StatusMessage)
end
end
-- Remember to wrap the function in a 'pcall' to prevent the script from breaking if the request fails
local success, message = pcall(request)
if not success then
print("Http Request failed:", message)
end