概要
方法
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 編碼字符串
-- 其他 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"), -- 在 Creator Hub 中設置
},
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 創建 WebStream 客戶端 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 JSONDecode
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 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
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 編碼字符串
-- 其他 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"), -- 在 Creator Hub 中設置
},
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 網址編碼
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 編碼字符串
-- 其他 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)