HttpService

顯示已棄用項目

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

無法建立
服務

HttpService 允許使用 RequestAsyncGetAsyncPostAsync 將 HTTP 請求從遊戲伺服器發送到 。此服務可讓遊戲與離開 Roblox 的網路服務,例如分析、資料儲存、遠端伺服器設定、錯誤報告、高級計算或實時通訊,進行整合。

HttpService 也包含 JSONEncodeJSONDecode 方法,這些方法對於與使用 JSON 格式的服務進行通信有用。此外,GenerateGUID 方法提供隨機的 128 位標籤,可以在各種情況下被視為具有概率上的獨特性。

您只應將 HTTP 請求傳送到信任的第三方平台,以避免讓您的體驗暴露於安全風險。

此屬性無法在執行階段時與其互動。

啟用 HTTP 請求

預設情況下,請求傳送方法不會啟用。若要傳送請求,您必須啟用 HTTP 請求對您的體驗。

在插件中使用

HttpService 可由工作室插件使用。他們可能這麼做以檢查更新、傳送使用資料、下載內容或其他業務邏輯。第一次插件嘗試這樣做時,使用者可能會被提示給插件許可與特定網址通訊。使用者可以隨時通過 插件管理 窗口接受、拒絕和撤銷這些權限。

插件也可以通過 localhost127.0.0.1 主機與同一台電腦上執行的其他軟件通信。透過執行與這些插件相容的程式,您可以將插件的功能擴展到 Studio 的正常功能之外,例如與電腦檔案系統互動。請注意,這類軟件必須與插件本身分開分配,如果你不小心,它可能會帶來安全風險。

額外考量
  • 有端口限制。您不能使用 port 或任何低於 port 的 port ,除了 和 。如果您嘗試使用被阻止的端口,您將收到 403 ForbiddenERR_ACCESS_DENIED 錯誤。
  • 對於每個 Roblox 遊戲伺服器,每分鐘最多有 500 個 HTTP 請求限制。超過此限制可能會導致請求傳送方法完全停止運作約 30 秒。
  • 無法向任何 Roblox 網站發出請求,例如 www.roblox.com。
  • 網路請求可能因為多種原因失敗,因此「防禦性編寫代碼」(使用 pcall()) 和設定請求失敗時的計畫很重要。
  • 雖然 http:// 協議被支持,但你應該在可能的情況下使用 https://
  • 傳送的請求應提供安全的認證形式,例如預先共享的秘密鍵,以便惡意行為者不能冒充為您的 Roblox 遊戲伺服器之一。
  • 注意網站上傳送請求的網路服務器的一般容量和速率限制政策。

範例程式碼

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).

Astronauts in Space

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.

Where is the International Space Station?

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).

New Pastebin Post

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 請求是否可以傳送到外部網站。

方法

屬性

HttpEnabled

本機使用者安全性
平行讀取

當設為 true 時,允許腳本向使用 HttpService:GetAsync()HttpService:PostAsync()HttpService:RequestAsync() 的網站發送請求。

此特性必須通過 Studio 的 遊戲設定 介面切換,或對 未發布 體驗設置此特性為 true 使用 指令欄

game:GetService("HttpService").HttpEnabled = true

方法

GenerateGUID

平行寫入

這個方法會生成一個 隨機普遍獨一標示符 (UUID) 字串。UUID 的十六位元被表示為 32 個十六進位 (基礎 16) 數字,顯示在五個以空格分開的形式 8-4-4-4-12 共 36 個字符,例如 123e4567-e89b-12d3-a456-426655440000

使用的UID規格是版本4(隨機),變體1(DCE 1.1、ISO/IEC 11578:1996)。這個版本的UUID最常用於簡單的原因是它們是隨機生成的,因為它們是完全隨機生成的。請注意,此版本沒有其他UUID版本所擁有的特定功能,例如編碼時間戳、MAC地址或時間基於排序,例如UUIDv7ULID

有超過 5.3×10 36 個獨特的 v4 UUID,其中在 103 兆個UID中找到重複的機率是一億分之一。

wrapInCurlyBraces 參數決定返回的字串是否被包裝在捲髮括號中({})。例個體、實例:

  • true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
  • false : db454790-7563-44ed-ab4b-397ff5df737b

參數

wrapInCurlyBraces: boolean

返回的字串應該被包裝在彎曲括號中( {} )。

預設值:true

返回

隨機生成的UUID。

範例程式碼

This example uses HttpService's GenerateGUID method to generate and print a universally unique identifier.

HttpService GenerateGUID

local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}

GetSecret

平行寫入

此方法返回以前為體驗添加到秘密儲存中的值。秘密內容無法印刷,當體驗在本地運行時不可用。

返回的 Secret 可以使用內置方法,例如 Secret:AddPrefix() 來轉換。期望作為 HTTP 邀請的一部分傳送。

欲了解更多信息,請參閱使用指南

參數

key: string
預設值:""

返回

JSONDecode

Variant
平行寫入

這個方法將 JSON 對象或陣列轉換為 Luau ,具有以下特性:

  • 表的鑰匙是字串或數字,但不是兩者都。如果 JSON 對象包含兩者,字串鑰匙將被忽略。
  • 空的 JSON 對象生成空的 Luau 表({})。
  • 如果 input 字串不是有效的 JSON 對物件,此方法將發出錯誤。

要將 Luau 表轉換為 JSON 對物件,請使用 HttpService:JSONEncode() 方法。

此方法無論HTTP請求是否啟用都可以使用。

參數

input: string

正在解碼的 JSON 對象。

預設值:""

返回

Variant

解碼的 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).

HttpService 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

平行寫入

這個方法會將 Luau 轉換為基於以下指南的 JSON 對象或數組:

  • 表的鑰匙必須是字串或數字。如果表包含兩個,則會優先使用陣列(字串鑰匙被忽略)。

  • 空的 Luau 表()會生成空的 JSON 數陣列。

  • nil 永遠不會生成。

  • 循環表引用會導致錯誤。

    這個方法允許值如 infnan 這樣的非有效 JSON。這可能會導致問題,如果您想在其他地方使用輸出的 JSON。

要反轉編碼過程並解碼 JSON 對物件,請使用 HttpService:JSONDecode() 方法。

此方法無論HTTP請求是否啟用都可以使用。

參數

input: Variant

輸入 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.

HttpService 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

平行寫入

這個方法 百分比編碼 給定的字串,使保留字符正確地以 % 和兩個十六進位字符編碼。

這對於使用 / 來格式化網址,或 媒體類型的資料 ( > ) 很有用。

例個體、實例,當您編碼 URL https://www.roblox.com/discover#/ 時,此方法返回 https%3A%2F%2Fwww%2Eroblox%2Ecom%2Fdiscover%23%2F

參數

input: string

要編碼的字串 (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).

HttpService UrlEncode

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).

New Pastebin Post

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 邀請。它的功能與 RequestAsync() 相似,除了接受 HTTP 請求參數作為方法參數,而不是單一字典,並只返回 HTTP 回應的體。一般來說,此方法只有在簡化形式中才有用,RequestAsync() 應在大多數情況下使用。

true 時,nocache 參數會防止此方法儲存以前的呼叫結果與相同的 url

參數

url: Variant

您要求資料的網址。

預設值:""
nocache: boolean

要求是否儲存(緩存)回應。

預設值:false
headers: Variant

用於指定一些 HTTP 請求頭痕。

預設值:""

返回

取得請邀請的回應身體。

範例程式碼

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).

Astronauts in Space

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.

Where is the International Space Station?

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 邀請。它的功能與 RequestAsync() 相似,除了接受 HTTP 請求參數作為方法參數,而不是單一字典,並只返回 HTTP 回應的體。一般來說,此方法只有在簡化形式中才有用,RequestAsync() 應在大多數情況下使用。

true 時,compress 參數控制大型請求體是否使用 gzip 壓縮。

參數

url: Variant

資料的目的地地址。

預設值:""
data: string

正在傳送的資料。

預設值:""
content_type: Enum.HttpContentType

修改請邀請傳送的 Content-Type 標題中的值。

預設值:"ApplicationJson"
compress: boolean

決定數據在傳送時是否壓縮( 壓縮 )。

預設值:false
headers: Variant

用於指定一些 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).

New Pastebin Post

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 請求,指定請求資料,例如目標網址、方法、頭籤和請求體資料。它返回一個描述收到的回應數據的辭典。可選擇使用 Enum.HttpCompression 壓縮請求。

請求字典欄位

<th>類型</th>
<th>需要</th>
<th>說明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>URL</code></td>
<td>字串</td>
<td>是</td>
<td>對此邀請求的目標網址。必須使用 <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>取得</code> 或 <code>頭部</code> HTTP 方法時被排除。傳送 JSON 或其他格式時,可能需要指定 <code>內容類型</code> 頭欄。</td>
</tr>
<tr>
<td><code>壓縮</code></td>
<td><code>Enum.Http壓縮</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>取得</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>放置</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>Body</code>數據中。</td>
<td>No</td>
</tr>
</tbody>
方法
HTTP 頭籤

在請求辭典中,您可以指定要在請邀請中使用的自訂 HTTP 頭枕。然而,有些頭欄無法指定。例如,Content-Length 是從請求身體中決定的。User-AgentRoblox-Id 被 Roblox 鎖定。其他標題,例如 AcceptCache-Control 使用預設值,但可以被覆蓋。更常見的是,一些 REST API 可能需要指定 API 鑰匙或其他服務認證在請求頭欄中。

RequestAsync() 方法不偵測到身體內容的格式。許多網站伺服器需要在傳送特定格式時設置 Content-Type 頭欄,以適當設置。其他方法的 HttpService 使用枚舉 Enum.HttpContentType ; 對於此方法,設置 Content-Type 標題適當: text/plain , text/xml , application/xml , application/jsonapplication/x-www-form-urlencoded 是對應枚舉值的替代 Content-Type 頭值。

回應字典欄位

RequestAsync() 返回包含以下欄位的辭典:


<th>類型</th>
<th>說明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>成功</code></td>
<td>Boolean 值</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() 如果回應超時或目標伺服器拒絕請邀請,就會發出錯誤。如果網路服務因為某種原因停止運作,就可能使使用此方法的腳本停止全部運作。通常有一個很好的想法是將此方法的呼叫包裝在 pcall() 中,並在必要資訊不可用的情況下優雅地處理失敗案件。

限制

目前傳送和接收 HTTP 請求的限制是每分鐘 500 個請求。超過此門檻的請求將失敗。此外,Roblox 域被排除。這意味著無法將 HTTP 請求傳送到任何 Roblox 擁有的網站,例如 www.roblox.com

參數

requestOptions: Dictionary

包含指向伺服器指定的資訊的辭典。

預設值:""

返回

包含指定伺服器的回應資訊的辭典。

範例程式碼

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.

Sending an HTTP Request

-- 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

活動