HttpService

显示已弃用

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

无法创建
服务

HttpService 允许使用 RequestAsyncGetAsyncPostAsync 将 HTTP 请求发送到游戏服务器。该服务允许游戏与 Roblox 以外的网络服务集成,例如分析、数据存储、远程服务器配置、错误报告、高级计算或实时通信。

HttpService 还包含 JSONEncodeJSONDecode 用于与使用 JSON 格式的服务进行通信的有用方法。此外,GenerateGUID 方法提供随机 128 位标签,可以在各种场景中视为概率独特。

您应该只向值得信赖的第三方平台发送 HTTP 请求,以避免让您的体验暴露于安全风险。

在运行时无法与此属性进行交互。

启用 HTTP 请求

默认情况下,请求发送方法不会启用。要发送请求,您必须启用 HTTP 请求对您的体验。

在插件中使用

HttpService 可由工作室插件使用。他们可能会这样做以检查更新、发送使用数据、下载内容或其他业务逻辑。第一次插件尝试这样做时,用户可能会被提示授予插件与特定网址通信的权限。用户可以随时通过 插件管理 窗口接受、拒绝和撤销这些权限。

插件也可以通过 localhost127.0.0.1 主机与同一台计算机上运行的其他软件通信。通过运行与这些插件兼容的程序,你可以将插件的功能扩展到 Studio 的普通功能之外,例如与你的计算机文件系统交互。注意,这类软件必须与插件本身分开分配,如果你不小心,它可能会带来安全风险。

额外考虑
  • 存在港口限制。您不能使用港口 1194 或任何低于 1024 的港口,除了 80443 。如果您尝试使用被阻止的端口,您将收到 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

使用的UUID规格是版本 4 (随机),变体 1 (DCE 1.1, ISO/IEC 11578:1996)。由于其简单,本版本的UUID最常被使用,因为它们是完全随机生成的。请注意,该版本没有其他 UUID 版本具有的特定功能,例如编码时间戳、MAC 地址或按时间排序,例如 UUIDv7ULID

有超过 5.3×10 36 独特的 v4 UUID,其中找到重复的概率在 103 兆个 UUID 中为百分之一。

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 永远不会生成。

  • 循环表引用会导致错误。

    这种方法允许不正确的 JSON 值,例如 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

写入并联

这个方法 百分比编码 一个给定的字符串,使保留字符正确地编码为 % 和两个十六进制字符。

这对于使用 HttpService:GetAsync() / HttpService:PostAsync()POST 媒体类型的数据格式化有用 (application/x-www-form-urlencoded) (Enum.HttpContentType.ApplicationUrlEncoded )。

例实例,当你编码 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

决定数据在发送时是否压缩( gzipped )。

默认值: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 请求,指定请求数据,例如目标 URL、方法、头部和请求体数据。它返回描述收到的响应数据的词典。可选地,请求可以使用 Enum.HttpCompression 压缩。

请求词典字段

<th>类型</th>
<th>需要</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>网址</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>GET</code> 或 <code>POST</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.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>获取</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>体</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

活动