Lớp công cụ
HttpService
*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.
Tóm Tắt
Thuộc Tính
Phương Pháp
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 |
Mẫu mã
Nhà du hành trong không gian
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Gửi yêu cầu đến URL điểm cuối của chúng tôi
local response = HttpService:GetAsync(URL_ASTROS)
-- Phân tích phản hồi JSON
local data = HttpService:JSONDecode(response)
-- Thông tin trong bảng dữ liệu phụ thuộc vào phản hồi JSON
if data.message == "success" then
print("Hiện có " .. data.number .. " nhà du hành trong không gian:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " đang ở trên " .. person.craft)
end
endTrạm Vũ trụ Quốc tế ở đâu?
local HttpService = game:GetService("HttpService")
-- Trạm Vũ trụ Quốc tế hiện đang ở đâu?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- Sử dụng pcall trong trường hợp có gì đó sai
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- Yêu cầu của chúng ta có bị thất bại hay JSON của chúng ta không phân tích được?
if not data then
return false
end
-- Kiểm tra hoàn toàn dữ liệu của chúng ta để xác minh tính hợp lệ. Điều này phụ thuộc vào điểm cuối mà bạn
-- đang gửi yêu cầu của mình. Như ví dụ này, điểm cuối này
-- được mô tả ở đây: 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("Trạm Vũ trụ Quốc tế hiện đang ở:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("Thành công")
else
print("Có gì đó sai xảy ra")
endBài viết mới trên Pastebin
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Khóa phát triển API của pastebin từ
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- giữ lại là "paste"
["api_paste_name"] = "HttpService:PostAsync", -- tên bài đăng
["api_paste_code"] = "Xin chào, thế giới", -- nội dung bài đăng
["api_paste_format"] = "text", -- định dạng bài đăng
["api_paste_expire_date"] = "10M", -- ngày hết hạn
["api_paste_private"] = "0", -- 0=công khai, 1=không công khai, 2=riêng tư
["api_user_key"] = "", -- khóa người dùng, nếu để trống sẽ đăng dưới dạng khách
}
-- API của pastebin sử dụng một chuỗi mã hóa URL cho dữ liệu post
-- Các API khác có thể sử dụng JSON, XML hoặc một định dạng khác
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) -- Xóa dấu & đầu tiên
-- Đây là dữ liệu mà chúng tôi đang gửi
print(data)
-- Gửi yêu cầu
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- Phản hồi sẽ là URL đến bài đăng mới (hoặc một chuỗi lỗi nếu có gì đó không ổn)
print(response)Mở Cloud qua HttpService
-- Hãy nhớ bật yêu cầu HTTP trong cài đặt trải nghiệm!
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}`, -- Cập nhật tư cách thành viên nhóm của người dùng
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- Khi gửi JSON, hãy thiết lập cái này!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Thiết lập trong Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("Phản hồi thành công:", response.StatusCode, response.StatusMessage)
else
print("Phản hồi trả về lỗi:", response.StatusCode, response.StatusMessage)
end
print("Nội dung phản hồi:\n", response.Body)
print("Header phản hồi:\n", HttpService:JSONEncode(response.Headers))
end
-- Hãy nhớ quấn hàm trong một 'pcall' để ngăn chặn kịch bản bị lỗi nếu yêu cầu thất bại
local success, message = pcall(request)
if not success then
print("Yêu cầu Http đã không gửi được:", message)
endTài Liệu Tham Khảo API
Thuộc Tính
Phương Pháp
CreateWebStreamClient
HttpService:CreateWebStreamClient(
Tham Số
Lợi Nhuận
Mẫu mã
HttpService TạoWebStreamClient 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") -- Giả sử bạn đã tải lên khóa API Gemini của mình dưới dạng một bí mật cục bộ
local url_with_secret = geminiSecret:AddPrefix(URL_GEMINI_SSE) -- Nhớ rằng các plugin không thể truy cập vào các bí mật cục bộ!
local function handleOpen(responseStatusCode, headers)
print("Kết nối đã mở với mã phản hồi:", responseStatusCode)
end
local function handleMessage(message)
-- Phân tích các sự kiện tùy thuộc vào loại luồng
print("Thông điệp luồng nhận được:", message)
end
local function request()
local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, {
Url = url_with_secret,
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- Khi gửi JSON, hãy thiết lập điều này!
},
Body = HttpService:JSONEncode({ contents = { parts = { text ="Giao thức SSE hoạt động như thế nào?" }}}),
})
local openConnection = sse_client.Opened:Connect(handleOpen)
local messageConnection = sse_client.MessageReceived:Connect(handleMessage)
sse_client.Closed:Wait()
openConnection:Disconnect()
messageConnection:Disconnect()
end
-- Nhớ đóng gói hàm trong một 'pcall' để ngăn chặn kịch bản bị hỏng nếu yêu cầu không thành công
local success, message = pcall(request)
if not success then
print("WebStreamClient không thành công:", message)
endHttpService TạoWebStreamClient RawStream
local HttpService = game:GetService("HttpService")
local LOCAL_LLM_PORT = "http://localhost:11434/api/generate?stream=true"
local function handleMessage(message)
-- Phân tích sự kiện tùy theo loại stream
-- Nếu tiêu đề Content-Type của phản hồi là JSON, bạn có thể giải mã nó như thế này:
local json = HttpService:JSONDecode(message)
end
local function handleError(responseStatusCode, errorMessage)
print("Lỗi stream với mã phản hồi:", responseStatusCode)
end
local function request()
local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, {
-- Máy chủ LLM Llama3.2 đang chạy cục bộ sử dụng Ollama
Url = LOCAL_LLM_PORT,
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- Khi gửi JSON, hãy đặt nó!
},
Body = HttpService:JSONEncode({ model="llama3.2", prompt ="Hãy kể cho tôi một trò đùa hài hước"}),
})
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
-- Nhớ bọc hàm trong một 'pcall' để ngăn kịch bản bị hỏng nếu yêu cầu thất bại
local success, message = pcall(request)
if not success then
print("WebStreamClient đã thất bại:", message)
endGenerateGUID
Tham Số
| Giá Trị Mặc Định: true |
Lợi Nhuận
Mẫu mã
HttpService GenerateGUID
local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Đầu ra ví dụ: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}GetAsync
Tham Số
url:Variant |
| Giá Trị Mặc Định: false |
headers:Variant |
Lợi Nhuận
Mẫu mã
Nhà du hành trong không gian
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Gửi yêu cầu đến URL điểm cuối của chúng tôi
local response = HttpService:GetAsync(URL_ASTROS)
-- Phân tích phản hồi JSON
local data = HttpService:JSONDecode(response)
-- Thông tin trong bảng dữ liệu phụ thuộc vào phản hồi JSON
if data.message == "success" then
print("Hiện có " .. data.number .. " nhà du hành trong không gian:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " đang ở trên " .. person.craft)
end
endTrạm Vũ trụ Quốc tế ở đâu?
local HttpService = game:GetService("HttpService")
-- Trạm Vũ trụ Quốc tế hiện đang ở đâu?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- Sử dụng pcall trong trường hợp có gì đó sai
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- Yêu cầu của chúng ta có bị thất bại hay JSON của chúng ta không phân tích được?
if not data then
return false
end
-- Kiểm tra hoàn toàn dữ liệu của chúng ta để xác minh tính hợp lệ. Điều này phụ thuộc vào điểm cuối mà bạn
-- đang gửi yêu cầu của mình. Như ví dụ này, điểm cuối này
-- được mô tả ở đây: 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("Trạm Vũ trụ Quốc tế hiện đang ở:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("Thành công")
else
print("Có gì đó sai xảy ra")
endJSONDecode
Tham Số
Lợi Nhuận
Variant
Mẫu mã
HttpService JSONDecode
local HttpService = game:GetService("HttpService")
local jsonString = [[
{
"message": "thành công",
"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 == "thành công" then
-- Vì tab["hello"] và tab.hello là tương đương,
-- bạn cũng có thể sử dụng data["info"]["points"] ở đây:
print("Tôi có " .. data.info.points .. " điểm")
if data.info.isLeader then
print("Tôi là người dẫn đầu")
end
print("Tôi có " .. #data.info.past_scores .. " điểm số trước")
print("Tất cả thông tin:")
for key, value in pairs(data.info) do
print(key, typeof(value), value)
end
endJSONEncode
Tham Số
input:Variant |
Lợi Nhuận
Mẫu mã
Mã Sáng tạo HttpService JSONEncode
local HttpService = game:GetService("HttpService")
local tab = {
-- Nhớ: những dòng này là tương đương
--["message"] = "thành công",
message = "thành công",
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(
Tham Số
url:Variant |
| Giá Trị Mặc Định: "ApplicationJson" |
| Giá Trị Mặc Định: false |
headers:Variant |
Lợi Nhuận
Mẫu mã
Bài viết mới trên Pastebin
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Khóa phát triển API của pastebin từ
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- giữ lại là "paste"
["api_paste_name"] = "HttpService:PostAsync", -- tên bài đăng
["api_paste_code"] = "Xin chào, thế giới", -- nội dung bài đăng
["api_paste_format"] = "text", -- định dạng bài đăng
["api_paste_expire_date"] = "10M", -- ngày hết hạn
["api_paste_private"] = "0", -- 0=công khai, 1=không công khai, 2=riêng tư
["api_user_key"] = "", -- khóa người dùng, nếu để trống sẽ đăng dưới dạng khách
}
-- API của pastebin sử dụng một chuỗi mã hóa URL cho dữ liệu post
-- Các API khác có thể sử dụng JSON, XML hoặc một định dạng khác
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) -- Xóa dấu & đầu tiên
-- Đây là dữ liệu mà chúng tôi đang gửi
print(data)
-- Gửi yêu cầu
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- Phản hồi sẽ là URL đến bài đăng mới (hoặc một chuỗi lỗi nếu có gì đó không ổn)
print(response)RequestAsync
Tham Số
Lợi Nhuận
Mẫu mã
Gửi một Yêu Cầu HTTP
-- Nhớ thiết lập cho phép yêu cầu HTTP trong cài đặt trải nghiệm!
local HttpService = game:GetService("HttpService")
local function request()
local response = HttpService:RequestAsync({
Url = "http://httpbin.org/post", -- Trang web này giúp gỡ lỗi các yêu cầu HTTP
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- Khi gửi JSON, hãy thiết lập cái này!
},
Body = HttpService:JSONEncode({ hello = "world" }),
})
if response.Success then
print("Mã trạng thái:", response.StatusCode, response.StatusMessage)
print("Nội dung phản hồi:\n", response.Body)
else
print("Yêu cầu đã thất bại:", response.StatusCode, response.StatusMessage)
end
end
-- Nhớ bọc hàm trong 'pcall' để ngăn chặn kịch bản bị hỏng nếu yêu cầu thất bại
local success, message = pcall(request)
if not success then
print("Yêu cầu Http đã thất bại:", message)
endMở Cloud qua HttpService
-- Hãy nhớ bật yêu cầu HTTP trong cài đặt trải nghiệm!
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}`, -- Cập nhật tư cách thành viên nhóm của người dùng
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- Khi gửi JSON, hãy thiết lập cái này!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Thiết lập trong Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("Phản hồi thành công:", response.StatusCode, response.StatusMessage)
else
print("Phản hồi trả về lỗi:", response.StatusCode, response.StatusMessage)
end
print("Nội dung phản hồi:\n", response.Body)
print("Header phản hồi:\n", HttpService:JSONEncode(response.Headers))
end
-- Hãy nhớ quấn hàm trong một 'pcall' để ngăn chặn kịch bản bị lỗi nếu yêu cầu thất bại
local success, message = pcall(request)
if not success then
print("Yêu cầu Http đã không gửi được:", message)
endUrlEncode
Tham Số
Lợi Nhuận
Mẫu mã
Mã dịch vụ HttpService UrlEncode
local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- Tiếng Pháp cho "Tôi đã đi xem phim"
local result = HttpService:UrlEncode(content)
print(result) --> Je%20suis%20all%C3%A9%20au%20cinema%2EBài viết mới trên Pastebin
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Khóa phát triển API của pastebin từ
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- giữ lại là "paste"
["api_paste_name"] = "HttpService:PostAsync", -- tên bài đăng
["api_paste_code"] = "Xin chào, thế giới", -- nội dung bài đăng
["api_paste_format"] = "text", -- định dạng bài đăng
["api_paste_expire_date"] = "10M", -- ngày hết hạn
["api_paste_private"] = "0", -- 0=công khai, 1=không công khai, 2=riêng tư
["api_user_key"] = "", -- khóa người dùng, nếu để trống sẽ đăng dưới dạng khách
}
-- API của pastebin sử dụng một chuỗi mã hóa URL cho dữ liệu post
-- Các API khác có thể sử dụng JSON, XML hoặc một định dạng khác
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) -- Xóa dấu & đầu tiên
-- Đây là dữ liệu mà chúng tôi đang gửi
print(data)
-- Gửi yêu cầu
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- Phản hồi sẽ là URL đến bài đăng mới (hoặc một chuỗi lỗi nếu có gì đó không ổn)
print(response)