概要
方法
CreateWebStreamClient(streamClientType: Enum.WebStreamClientType,requestOptions: Dictionary):WebStreamClient |
GenerateGUID(wrapInCurlyBraces: boolean):string |
JSONDecode(input: string):Variant |
JSONEncode(input: Variant):string |
PostAsync(url: Variant,data: string,content_type: Enum.HttpContentType,compress: boolean,headers: Variant):string |
RequestAsync(requestOptions: Dictionary):Dictionary |
代码示例
太空中的宇航员
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新的 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)通过 HttpService 打开云
-- 记得在体验设置中启用 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)
endAPI 参考
属性
方法
CreateWebStreamClient
HttpService:CreateWebStreamClient(
参数
代码示例
HttpService 创建WebStreamClient SSE
local HttpService = game:GetService("HttpService")
local URL_GEMINI_SSE = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key="
local geminiSecret = HttpService:GetSecret("gemini_secret") -- 假设您已经将您的 Gemini API 密钥作为本地密钥上传
local url_with_secret = geminiSecret:AddPrefix(URL_GEMINI_SSE) -- 请记住,插件无法访问本地密钥!
local function handleOpen(responseStatusCode, headers)
print("流已打开,响应代码为:", responseStatusCode)
end
local function handleMessage(message)
-- 根据流类型解析事件
print("收到流消息:", message)
end
local function request()
local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, {
Url = url_with_secret,
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- 发送 JSON 时,请设置此项!
},
Body = HttpService:JSONEncode({ contents = { parts = { text ="SSE 协议是如何工作的?" }}}),
})
local openConnection = sse_client.Opened:Connect(handleOpen)
local messageConnection = sse_client.MessageReceived:Connect(handleMessage)
sse_client.Closed:Wait()
openConnection:Disconnect()
messageConnection:Disconnect()
end
-- 请记得将函数包装在 'pcall' 中,以防请求失败导致脚本中断
local success, message = pcall(request)
if not success then
print("WebStreamClient 失败:", message)
endHttpService 创建 WebStreamClient 原始流
local HttpService = game:GetService("HttpService")
local LOCAL_LLM_PORT = "http://localhost:11434/api/generate?stream=true"
local function handleMessage(message)
-- 根据流类型解析事件
-- 如果响应的 Content-Type 头是 JSON,你可以这样解码它:
local json = HttpService:JSONDecode(message)
end
local function handleError(responseStatusCode, errorMessage)
print("流错误,响应代码:", responseStatusCode)
end
local function request()
local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, {
-- Llama3.2 LLM 服务器在本地运行,使用 Ollama
Url = LOCAL_LLM_PORT,
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- 发送 JSON 时,设置此项!
},
Body = HttpService:JSONEncode({ model="llama3.2", prompt ="告诉我一个有趣的笑话"}),
})
local messageConnection = sse_client.MessageReceived:Connect(handleMessage)
local errorConnection = sse_client.Error:Connect(handleError)
sse_client.Closed:Wait()
messageConnection:Disconnect()
errorConnection:Disconnect()
sse_client:close()
end
-- 别忘了将函数包裹在 'pcall' 中,以防请求失败而导致脚本中断
local success, message = pcall(request)
if not success then
print("WebStreamClient 失败:", message)
endGenerateGUID
GetAsync
参数
url:Variant |
| 默认值:false |
headers:Variant |
返回
代码示例
太空中的宇航员
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("出错了")
endJSONDecode
参数
返回
Variant
代码示例
HttpService JSON解码
local HttpService = game:GetService("HttpService")
local jsonString = [[
{
"message": "成功",
"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 == "成功" 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
endJSONEncode
参数
input:Variant |
返回
代码示例
HttpService JSON编码
local HttpService = game:GetService("HttpService")
local tab = {
-- 请记住:这些行是等价的
--["message"] = "成功",
message = "成功",
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
HttpService:PostAsync(
参数
url:Variant |
| 默认值:"ApplicationJson" |
| 默认值:false |
headers:Variant |
返回
代码示例
新的 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)RequestAsync
参数
代码示例
发送 HTTP 请求
-- 请记得在体验设置中启用 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通过 HttpService 打开云
-- 记得在体验设置中启用 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)
endUrlEncode
参数
返回
代码示例
HttpService 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新的 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)