HttpService
*このコンテンツは、ベータ版のAI(人工知能)を使用して翻訳されており、エラーが含まれている可能性があります。このページを英語で表示するには、 こちら をクリックしてください。
HttpService は、RequestAsync、GetAsync、PostAsync を使用してゲームサーバーから HTTP リクエストを送信できます。このサービスでは、ゲームがアナリティクス、データストレージ、リモートサーバー構成、エラー報告、高度な計算、またはリアルタイムコミュニケーションなどのオフ Roblox ウェブサービスと統合できます。さらに、いくつかの Roblox ウェブ API も HttpService を介してアクセスできます (以下を参照)。
HttpService には、JSONEncode および JSONDecode 方法も含まれており、JSON 形式を使用するサービスとの通信に便利な方法も含まれています。さらに、GenerateGUID メソッドは、ランダムな 128ビットラベルを提供し、さまざまなシナリオで確率的に唯一として扱うことができます。
エクスペリエンスをセキュリティリスクにさらすことを避けるために、信頼できる第三者プラットフォームにのみ HTTP リクエストを送信する必要があります。
このプロパティは、実行時にインタラクトできません。
HTTP リクエストを有効にする
リクエスト送信方法はデフォルトで有効になっていません。リクエストを送信するには、エクスペリエンスのために HTTP リクエストを有効にする 必要があります。
プラグインで使用
HttpService は、Studio プラグインで使用できます。アップデートをチェックしたり、使用データを送信したり、コンテンツをダウンロードしたり、他のビジネスロジックを実行するためにこれを行う可能性があります。プラグインがこれを行おうとする最初の時に、ユーザーに特定のウェブアドレスと通信する権限をプラグインに与えるよう求められる可能性があります。ユーザーは、 プラグイン管理 ウィンドウを通じて、いつでもそのような権限を承認、拒否、撤回できます。
プラグインは、localhost および 127.0.0.1 ホストを介して、同じコンピュータ上で実行中の他のソフトウェアとも通信できます。このプラグインと互換性のあるプログラムを実行することで、プラグインの機能を通常の Studio 機能以上に拡張できます、例えばコンピュータのファイルシステムとの対話などそのようなソフトウェアは、プラグイン自体とは別に配布する必要があり、注意しなければセキュリティ上の脅威になる可能性があります。
Roblox ドメインを呼び出す
HttpService 現在、オープンクラウドエンドポイントのサブセットのみを呼び出すことができます。このセットを時間をかけて拡張する予定ですので、特定のエンドポイントを見たい場合は、フィードバックボタンを使用してください:
グループ
データストア
HttpService に対する現在の制限により、Roblox ドメインの URL パスパラメータには、アルファベット数字のみと - 文字のみが許可されています。これは、他の特殊文字を持つデータストア/エントリが、現在 HttpService からアクセスできないことを意味します。
持ち物アイテム
クリエイターストア
これらのエンドポイントを呼び出す方法は、HttpService を介して他のエンドポイントを呼び出す方法と同じです。唯一の違いは、リクエストにオープンクラウド API キーを含める必要があることです:
- リクエストを作成 (下のコード例)。
制限には以下が含まれます:
- ヘッダーのみ x-api-key と content-type のみが許可されています。
- ヘッダー x-api-key は Secret でなければなりません。
- URLパスパラメータでは、アルファ数字と - 文字のみが許可されています。
- のみが https:// プロトコルがサポートされています。
レート制限
Roblox ゲームサーバーごとに、分ごとに 500 HTTP リクエストの制限があります。これを超えると、リクエスト送信メソッドが約 30秒間完全に停止する可能性があります。Your pcall() は、「リクエスト数が制限を超えた」というメッセージで失敗する可能性もあります。
クラウドリクエストを開くと、他のすべてのリクエストに適用される 500 HTTPリクエスト per minute の総制限が消費されます。
各オープンクラウドエンドポイントには、APIキー所有者ごとに独自の制限があり、呼び出しがどこから来ても強制されます(HttpService、ウェブなど)。次のヘッダーはすべての応答とともに返され、制限と残りのクオータを表示できます:
- x-ratelimit-limit - API キー所有者が作成できるリクエストの合計数 (通常は 1 分ごと)。
- x-ratelimit-remaining - API キーが使用したリクエストの数は、まだ作成できます。この数が 0 で HTTP 429 応答ステータスコードを受信した場合、このエンドポイントのレート制限に達しました。
- x-ratelimit-reset - レート制限がリセットされる前の秒数 (つまり x-ratelimit-remaining が x-ratelimit-limit にリセットする前)。
追加の注意事項
- ポート制限があります。ポート 1194 または 1024 以下のポートを使用できません、除き 80 と 443 のみ。ブロックされたポートを使おうとすると、403 Forbidden または ERR_ACCESS_DENIED エラーが発生します。
- Web リクエストは多くの理由で失敗する可能性があるため、「防御的にコードを使用」(pcall())し、リクエストが失敗したときのプランを持つことが重要です。
- http:// プロトコルはサポートされていますが、可能な限り https:// を使用する必要があります。
- 送信されたリクエストは、プリシェアされた秘密鍵などの安全な認証形式を提供して、悪意のあるアクターが Roblox ゲームサーバーの 1つとして偽装できないようにする必要があります。
- リクエストが送信されるウェブサーバーの一般的な容量とレート制限政策を認識してください。
コードサンプル
このコードサンプルは、HttpService の GetAsync を使用して、オープン通知、NASAからデータを提供するウェブサービスにリクエストを送信します。リクエストは、現在宇宙にいるアストロノットの数に関する情報を提供するエンドポイントに送信されます。応答は JSON 形式で提供されるので、JSONDecode を使用して解析されます。最後に、応答データは処理され、出力に印刷されます。
ソースコードをスクリプトに貼り付けてこのスクリプトをテストします(HttpServiceはローカルスクリプトで使用できません)。また、ゲーム設定 (ホーム > ゲーム設定) で HTTP リクエストを有効にすることを忘れないでください。
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- 我々のエンドポイント URL にリクエストを送信する
local response = HttpService:GetAsync(URL_ASTROS)
-- JSON 応答を解析する
local data = HttpService:JSONDecode(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)
This code sample demonstrates sending a single HTTP PATCH request with JSON data to the Open Cloud Update Group Membership endpoint. Every Open Cloud endpoint requires adding your API key to the x-api-key header to receive a successful response. The generated API key must be stored as a Secret that can later be retrieved with HttpService:GetSecret("API KEY SECRET NAME").
-- Remember to set enable HTTP Requests in game settings!
local HttpService = game:GetService("HttpService")
local groupId = "your_group_id"
local membershipId = "your_membership_id"
local roleId = "your_role_id"
local function request()
local response = HttpService:RequestAsync({
Url = `https://apis.roblox.com/cloud/v2/groups/{groupId}/memberships/{membershipId}`, -- Updates a user's group membership
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- When sending JSON, set this!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Set in Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("The response was successful:", response.StatusCode, response.StatusMessage)
else
print("The response returned an error:", response.StatusCode, response.StatusMessage)
end
print("Response body:\n", response.Body)
print("Response headers:\n", HttpService:JSONEncode(response.Headers))
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("The Http request failed to send:", message)
end
概要
プロパティ
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
方法
GenerateGUID
パラメータ
戻り値
コードサンプル
local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}
JSONDecode
パラメータ
戻り値
コードサンプル
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
パラメータ
戻り値
コードサンプル
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
パラメータ
戻り値
コードサンプル
local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- 「映画に行った」フランス語
local result = HttpService:UrlEncode(content)
print(result) --> Je%20suis%20all%C3%A9%20au%20cinema%2E
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
パラメータ
戻り値
コードサンプル
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- 我々のエンドポイント URL にリクエストを送信する
local response = HttpService:GetAsync(URL_ASTROS)
-- JSON 応答を解析する
local data = HttpService:JSONDecode(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
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
パラメータ
戻り値
コードサンプル
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
パラメータ
戻り値
コードサンプル
-- 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
-- Remember to set enable HTTP Requests in game settings!
local HttpService = game:GetService("HttpService")
local groupId = "your_group_id"
local membershipId = "your_membership_id"
local roleId = "your_role_id"
local function request()
local response = HttpService:RequestAsync({
Url = `https://apis.roblox.com/cloud/v2/groups/{groupId}/memberships/{membershipId}`, -- Updates a user's group membership
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- When sending JSON, set this!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Set in Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("The response was successful:", response.StatusCode, response.StatusMessage)
else
print("The response returned an error:", response.StatusCode, response.StatusMessage)
end
print("Response body:\n", response.Body)
print("Response headers:\n", HttpService:JSONEncode(response.Headers))
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("The Http request failed to send:", message)
end