HttpService

Hiển Thị Bản Đã Lỗi Thời

*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.

Không Thể Tạo
Dịch Vụ

HttpService cho phép các yêu cầu HTTP được gửi từ máy chủ trò chơi bằng cách sử dụng RequestAsync , GetAsyncPostAsync .Dịch vụ này cho phép các trò chơi được tích hợp với các dịch vụ web ngoài Roblox như phân tích, lưu trữ dữ liệu, cấu hình máy chủ độ xa, báo cáo lỗi, tính toán nâng cao hoặc giao tiếp thời gian thực.Ngoài ra, một vài API web Roblox cũng có thể truy cập thông qua HttpService

HttpService cũng chứa các phương pháp JSONEncodeJSONDecode có ích cho việc giao tiếp với các dịch vụ sử dụng định dạng JSON .Ngoài ra, phương pháp GenerateGUID cung cấp các nhãn ngẫu nhiên 128‑bit có thể được xử lý như là duy nhất theo nhiều tình huống khác nhau.

Bạn chỉ nên gửi yêu cầu HTTP đến các nền tảng bên thứ ba đáng tin cậy để tránh làm cho trải nghiệm của bạn dễ bị xâm phạm vào các rủi ro bảo mật.

Tính năng này không thể tương tác được khi chạy thời gian thực.

Bật yêu cầu HTTP

Các phương pháp gửi yêu cầu không được bật mặc định. Để gửi yêu cầu, bạn phải bật yêu cầu HTTP cho trải nghiệm của bạn.

Sử dụng trong plugin

HttpService có thể được sử dụng bởi các plugin Studio.Họ có thể làm điều này để kiểm tra cập nhật, gửi dữ liệu sử dụng, tải nội dung hoặc logic kinh doanh khác.Lần đầu tiên một plugin cố gắng làm điều này, người dùng có thể được yêu cầu cho phép plugin giao tiếp với địa chỉ web cụ thể.Một người dùng có thể chấp nhận, từ chối và thu hồi các quyền như vậy bất cứ lúc nào thông qua cửa sổ Quản lý plugin .

Các plugin cũng có thể giao tiếp với các phần mềm khác đang chạy trên cùng một máy tính thông qua các host localhost127.0.0.1.Bằng cách chạy các chương trình tương thích với các plugin như vậy, bạn có thể mở rộng chức năng của plugin của bạn ngoài các chức năng bình thường của Studio, chẳng hạn như tương tác với hệ thống tập tin của máy tính của bạn.Hãy lưu ý rằng phần mềm như vậy phải được phân phối riêng biệt khỏi chính plugin và có thể gây nguy hiểm bảo mật nếu bạn không cẩn thận.

Gọi các domain Roblox

HttpService hiện tại chỉ có thể gọi một phần phụ của các điểm cuối Open Cloud.Chúng tôi dự định mở rộng bộ này theo thời gian nên xin hãy sử dụng nút Phản hồi nếu bạn có các điểm cuối cụ thể mà bạn muốn xem:

Nhóm
Kho dữ liệu

Do các hạn chế hiện tại về HttpService , chỉ các ký tự alphanumeric và nhân vật - được phép trong các tham số đường dẫn URL cho các trang web của Roblox.Điều này có nghĩa là Các kho dữ liệu/mục với các ký tự đặc biệt khác hiện không thể truy cập từ HttpService .

Vật phẩm Kho hàng
Cửa hàng Nhà sáng lập

Bạn có thể gọi các điểm cuối này theo cùng cách mà bạn gọi bất kỳ điểm cuối khác thông qua HttpService .Sự khác biệt duy nhất là bạn phải bao gồm một chìa khóa API Mở đám mây trong yêu cầu:

  1. Tạo yêu cầu ( ví dụ mã bên dưới ).

Các giới hạn bao gồm các điều sau:

  • Chỉ các tiêu đề x-api-keycontent-type được phép.
  • Tiêu đề x-api-key phải là Secret.
  • Chỉ các ký tự alphanumeric và nhân vật - là được phép trong các tham số đường dẫn URL.
  • Chỉ có giao thức https:// được hỗ trợ.
Giới hạn tốc độ

Đối với mỗi máy chủ trò chơi Roblox, có giới hạn 500 yêu cầu HTTP mỗi phút.Vượt quá điều này có thể khiến các phương pháp gửi yêu cầu dừng hoàn toàn trong khoảng 30 giây.Your pcall() cũng có thể thất bại với một thông điệp "Số yêu cầu vượt quá giới hạn."

  • Yêu cầu Mở đám mây tiêu thụ giới hạn tổng cộng của 500 yêu cầu HTTP mỗi phút áp dụng cho tất cả các yêu cầu khác.

  • Mỗi điểm cuối Open Cloud có giới hạn riêng cho mỗi chủ sở hữu chìa khóa API (có thể là người dùng hoặc nhóm) mà được áp dụng bất kể nguồn gọi đến từ đâu (HttpService , web, v.v.).Các tiêu đề sau đây được trả với mỗi phản hồi và cho phép bạn xem giới hạn và phần còn lại của quota của bạn:

    • x-ratelimit-limit - Tổng số yêu cầu được phép thực hiện cho mỗi chủ sở hữu chìa khóa API (thường là mỗi phút).
    • x-ratelimit-remaining - Số yêu cầu mà chìa khóa API đã sử dụng vẫn được phép thực hiện.Nếu số này là 0 và bạn nhận được mã trạng thái phản hồi HTTP 429, thì bạn đã đạt đến giới hạn tốc độ cho điểm cuối này.
    • x-ratelimit-reset - Số giây còn lại trước khi giới hạn tốc độ được đặt lại (tức là trước khi x-ratelimit-remaining được đặt lại thành x-ratelimit-limit ).
Xem xét bổ sung
  • Có hạn chế cổng.Bạn không thể sử dụng cổng 1194 hoặc bất kỳ cổng nào dưới 1024 , ngoại trừ 80443 .Nếu bạn cố gắng sử dụng một cổng bị chặn, bạn sẽ nhận được một trong hai lỗi 403 Forbidden hoặc ERR_ACCESS_DENIED.
  • Yêu cầu web có thể thất bại vì nhiều lý do, vì vậy việc "viết mã phòng thủ" (sử dụng pcall()) là rất quan trọng và có kế hoạch cho khi yêu cầu thất bại.
  • Mặc dù giao thức http:// được hỗ trợ, bạn nên sử dụng https:// ở bất cứ đâu có thể.
  • Các yêu cầu được gửi nên cung cấp một hình thức xác thực an toàn, chẳng hạn như một chìa khóa bí mật được chia sẻ trước, để các tác nhân xấu không thể giả vờ là một trong các máy chủ trò chơi Roblox của bạn.
  • Hãy lưu ý đến công suất và chính sách giới hạn tốc độ chung của các máy chủ web mà các yêu cầu được gửi đi.

Mẫu mã

Ví dụ mã này sử dụng HttpService's GetAsync để gửi yêu cầu tới Mở thông báo, một dịch vụ web cung cấp dữ liệu từ NASA.Yêu cầu được gửi đến một điểm cuối cung cấp thông tin về số lượng phi hành gia hiện đang ở trong không gian.Phản hồi được cung cấp trong định dạng JSON, vì vậy nó được giải mã bằng cách sử dụng JSONDecode.Cuối cùng, dữ liệu phản hồi được xử lý và in ra Đầu ra.

Thử nghiệm kịch bản này bằng cách dán mã nguồn vào một Kịch bản (HttpService không thể được sử dụng bởi LocalScripts).Ngoài ra, hãy chắc chắn để bật yêu cầu HTTP trong Cài đặt trò chơi của bạn (Trang chủ > Cài đặt trò chơi).

Phi hành gia 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 cuối cùng 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("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)

This code sample demonstrates sending a single HTTP PATCH request with JSON data to the Open Cloud Update Group Membership endpoint. Every Open Cloud endpoint requires adding your API key to the x-api-key header to receive a successful response. The generated API key must be stored as a Secret that can later be retrieved with HttpService:GetSecret("API KEY SECRET NAME").

Open Cloud via HttpService

-- Remember to set enable HTTP Requests in game settings!
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}`, -- Updates a user's group membership
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- When sending JSON, set this!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Set in Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("The response was successful:", response.StatusCode, response.StatusMessage)
else
print("The response returned an error:", response.StatusCode, response.StatusMessage)
end
print("Response body:\n", response.Body)
print("Response headers:\n", HttpService:JSONEncode(response.Headers))
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("The Http request failed to send:", message)
end

Tóm Tắt

Thuộc Tính

  • Bảo Mật Người Dùng Cục Bộ
    Đọc Song Song

    Chỉ ra xem yêu cầu HTTP có thể được gửi đến các trang web bên ngoài không.

Phương Pháp

Thuộc Tính

HttpEnabled

Bảo Mật Người Dùng Cục Bộ
Đọc Song Song

Phương Pháp

GenerateGUID

Ghi Song Song

Tham Số

wrapInCurlyBraces: boolean
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) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}

GetSecret

Ghi Song Song

Tham Số

key: string
Giá Trị Mặc Định: ""

Lợi Nhuận

JSONDecode

Variant
Ghi Song Song

Tham Số

input: string
Giá Trị Mặc Định: ""

Lợi Nhuận

Variant

Mẫu mã

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

Ghi Song Song

Tham Số

input: Variant
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

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

Ghi Song Song

Tham Số

input: string
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

HttpService UrlEncode Định dạng

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%2E
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

Sinh Lợi

Tham Số

url: Variant
Giá Trị Mặc Định: ""
nocache: boolean
Giá Trị Mặc Định: false
headers: Variant
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

Phi hành gia 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 cuối cùng 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("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
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

Sinh Lợi

Tham Số

url: Variant
Giá Trị Mặc Định: ""
data: string
Giá Trị Mặc Định: ""
content_type: Enum.HttpContentType
Giá Trị Mặc Định: "ApplicationJson"
compress: boolean
Giá Trị Mặc Định: false
headers: Variant
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

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

Sinh Lợi

Tham Số

requestOptions: Dictionary
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

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
Open Cloud via HttpService

-- Remember to set enable HTTP Requests in game settings!
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}`, -- Updates a user's group membership
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- When sending JSON, set this!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Set in Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("The response was successful:", response.StatusCode, response.StatusMessage)
else
print("The response returned an error:", response.StatusCode, response.StatusMessage)
end
print("Response body:\n", response.Body)
print("Response headers:\n", HttpService:JSONEncode(response.Headers))
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("The Http request failed to send:", message)
end

Sự Kiện