HttpService 允许从游戏服务器发送HTTP请求,使用 RequestAsync, GetAsync 和 PostAsync。该服务允许将游戏与第三方Web服务集成,例如分析、数据存储、 远程服务器配置、错误报告、高级计算或实时通信。此外,它还可以调用部分Open Cloud API。
有关这些用例的更多信息,请参见 体验内HTTP请求。
HttpService 还包含 JSONEncode 和 JSONDecode 方法,这对与使用 JSON 格式的服务进行通信很有用。此外,GenerateGUID 方法提供随机的128位标签,可以在多种场景中被视为概率唯一。
仅向可信的第三方平台发送HTTP请求,以避免对您的体验引入不必要的安全风险。
代码示例
这个代码示例使用 HttpService 的 GetAsync 方法向 Open Notify 发送请求,这是一个提供 NASA 数据的网络服务。请求是发送到一个提供当前在太空中有多少宇航员的信息的端点。响应是以 JSON 格式提供的,因此它使用 JSONDecode 进行解析。最后,响应数据被处理并打印到输出。
通过将源代码粘贴到脚本中来测试这个脚本(HttpService 不能在 LocalScripts 中使用)。此外,请确保在游戏设置中启用 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("目前有 " .. data.number .. " 名宇航员在太空中:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " 在 " .. person.craft)
end
end
此代码示例使用 HttpService 的 GetAsync 请求一个端点 在 Open Notify 上,这是一个 提供来自 NASA 信息的网站。该端点提供国际空间站当前位置信息。此示例使用 防御性编码技术,在进行网络请求时应该使用它。 它将对 GetAsync 和 JSONDecode 的调用封装在 pcall 中,这样可以保护我们的 脚本在这两者中的任何一个失败时不引发错误。然后,它在使用之前检查原始 响应的所有正确数据。这一切都放在一个 函数中,该函数根据请求的成功与否返回 true 或 false。
每当您处理网络请求时,您应该为任何事情出错做好准备。 或许您的网络端点发生了变化或出现故障 - 您不想让您的游戏脚本引发错误并破坏您的游戏。 您希望优雅地处理成功 和失败 - 如果您的数据不可用,请做好计划。使用 pcall 并对 您的数据进行充分的有效性检查(if 语句),以确保您获得的确实是您所期望的内容。
local HttpService = game:GetService("HttpService")
-- 国际空间站现在在哪里?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- 使用 pcall 以防出现问题
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- 我们的请求失败了还是 JSON 解析失败了?
if not data then
return false
end
-- 彻底检查我们的数据的有效性。这取决于您要发送请求的端点。
-- 对于这个示例,这个端点在这里描述: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("国际空间站目前位于:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("成功")
else
print("出错了")
end
Pastebin.com 是一个允许用户粘贴文本(通常是源代码)以供他人公开查看的网站。此代码示例使用 HttpService 的 PostAsync 和 Pastebin 的 Web API 自动在网站上创建一个新的公开粘贴。由于 pastebin 的 API 设计为接收 URL 编码字符串的数据,因此代码使用 for 循环将 dataFields 表转换为 URL 编码字符串,例如 hello=world&foo=bar。这被用作 HTTP POST 数据。
首先访问 pastebin.com/api#1 获取 API 密钥以测试此代码(您需要一个 pastebin 账户才能执行此操作)。然后,将您的独特开发者 API 密钥粘贴到代码示例的 dataFields 表中的 api_dev_key 字段中。填写您想要发布的其他信息,然后在脚本(而不是 LocalScript)中运行此代码。如果一切顺利,您将在输出窗口中获得新粘贴的网址(或从 pastebin 返回的一些错误字符串)。
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API 开发者密钥来自
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- 保持为 "paste"
["api_paste_name"] = "HttpService:PostAsync", -- 粘贴名称
["api_paste_code"] = "Hello, world", -- 粘贴内容
["api_paste_format"] = "text", -- 粘贴格式
["api_paste_expire_date"] = "10M", -- 过期日期
["api_paste_private"] = "0", -- 0=公开,1=不公开,2=私有
["api_user_key"] = "", -- 用户密钥,如果为空则作为访客发布
}
-- Pastebin API 使用 URL 编码字符串作为 POST 数据
-- 其他 API 可能使用 JSON、XML 或其他格式
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) -- 删除第一个 &
-- 这是我们要发送的数据
print(data)
-- 发出请求
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- 响应将是新粘贴的 URL(或如果出现问题,则是错误字符串)
print(response)
此代码示例演示了如何向开放云更新组成员身份端点发送单个HTTP PATCH请求,并携带JSON数据。 每个开放云端点都要求将您的API密钥添加到x-api-key头,以便获得成功的响应。生成的API密钥必须存储为Secret,以后可以通过HttpService:GetSecret("API KEY SECRET NAME")来检索。
-- 请记得在游戏设置中启用HTTP请求!
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}`, -- 更新用户的组成员身份
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- 发送JSON时,请设置此项!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- 在创作者中心设置
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("响应成功:", response.StatusCode, response.StatusMessage)
else
print("响应返回错误:", response.StatusCode, response.StatusMessage)
end
print("响应主体:\n", response.Body)
print("响应头:\n", HttpService:JSONEncode(response.Headers))
end
-- 请记得将函数包装在'pcall'中,以防请求失败时脚本崩溃
local success, message = pcall(request)
if not success then
print("Http请求未发送成功:", message)
end
概要
方法
属性
HttpEnabled
方法
GenerateGUID
参数
返回
代码示例
local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> 示例输出: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}
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("目前有 " .. data.number .. " 名宇航员在太空中:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " 在 " .. person.craft)
end
end
local HttpService = game:GetService("HttpService")
-- 国际空间站现在在哪里?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- 使用 pcall 以防出现问题
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- 我们的请求失败了还是 JSON 解析失败了?
if not data then
return false
end
-- 彻底检查我们的数据的有效性。这取决于您要发送请求的端点。
-- 对于这个示例,这个端点在这里描述: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("国际空间站目前位于:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("成功")
else
print("出错了")
end
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
-- 因为 tab["hello"] 和 tab.hello 是等价的,
-- 你也可以在这里使用 data["info"]["points"]:
print("我有 " .. data.info.points .. " 分")
if data.info.isLeader then
print("我是领导者")
end
print("我有 " .. #data.info.past_scores .. " 个过去的分数")
print("所有信息:")
for key, value in pairs(data.info) do
print(key, typeof(value), value)
end
end
JSONEncode
参数
返回
代码示例
local HttpService = game:GetService("HttpService")
local tab = {
-- 请记住:这些行是等价的
--["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)
PostAsync
参数
返回
代码示例
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API 开发者密钥来自
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- 保持为 "paste"
["api_paste_name"] = "HttpService:PostAsync", -- 粘贴名称
["api_paste_code"] = "Hello, world", -- 粘贴内容
["api_paste_format"] = "text", -- 粘贴格式
["api_paste_expire_date"] = "10M", -- 过期日期
["api_paste_private"] = "0", -- 0=公开,1=不公开,2=私有
["api_user_key"] = "", -- 用户密钥,如果为空则作为访客发布
}
-- Pastebin API 使用 URL 编码字符串作为 POST 数据
-- 其他 API 可能使用 JSON、XML 或其他格式
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) -- 删除第一个 &
-- 这是我们要发送的数据
print(data)
-- 发出请求
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- 响应将是新粘贴的 URL(或如果出现问题,则是错误字符串)
print(response)
RequestAsync
参数
返回
代码示例
-- 请记得在游戏设置中启用 HTTP 请求!
local HttpService = game:GetService("HttpService")
local function request()
local response = HttpService:RequestAsync({
Url = "http://httpbin.org/post", -- 该网站帮助调试 HTTP 请求
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- 发送 JSON 时,请设置此项!
},
Body = HttpService:JSONEncode({ hello = "world" }),
})
if response.Success then
print("状态码:", response.StatusCode, response.StatusMessage)
print("响应正文:\n", response.Body)
else
print("请求失败:", response.StatusCode, response.StatusMessage)
end
end
-- 请记得将函数包装在 'pcall' 中,以防请求失败时脚本崩溃
local success, message = pcall(request)
if not success then
print("HTTP 请求失败:", message)
end
-- 请记得在游戏设置中启用HTTP请求!
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}`, -- 更新用户的组成员身份
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- 发送JSON时,请设置此项!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- 在创作者中心设置
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("响应成功:", response.StatusCode, response.StatusMessage)
else
print("响应返回错误:", response.StatusCode, response.StatusMessage)
end
print("响应主体:\n", response.Body)
print("响应头:\n", HttpService:JSONEncode(response.Headers))
end
-- 请记得将函数包装在'pcall'中,以防请求失败时脚本崩溃
local success, message = pcall(request)
if not success then
print("Http请求未发送成功:", message)
end
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 开发者密钥来自
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- 保持为 "paste"
["api_paste_name"] = "HttpService:PostAsync", -- 粘贴名称
["api_paste_code"] = "Hello, world", -- 粘贴内容
["api_paste_format"] = "text", -- 粘贴格式
["api_paste_expire_date"] = "10M", -- 过期日期
["api_paste_private"] = "0", -- 0=公开,1=不公开,2=私有
["api_user_key"] = "", -- 用户密钥,如果为空则作为访客发布
}
-- Pastebin API 使用 URL 编码字符串作为 POST 数据
-- 其他 API 可能使用 JSON、XML 或其他格式
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) -- 删除第一个 &
-- 这是我们要发送的数据
print(data)
-- 发出请求
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- 响应将是新粘贴的 URL(或如果出现问题,则是错误字符串)
print(response)