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.
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 , GetAsync và PostAsync .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.
HttpService cũng chứa các phương pháp JSONEncode và JSONDecode 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 localhost và 127.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.
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ừ 80 và 443 .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.
- Đố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.
- Yêu cầu không thể được gửi đến bất kỳ trang web Roblox nào, chẳng hạn như www.roblox.com.
- 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ã
This code sample uses HttpService's GetAsync to make a request to Open Notify, a web service that provides data from NASA. The request is made to an endpoint that provides information on how many astronauts are currently in space. The response is provided in JSON format, so it is parsed using JSONDecode. Finally, the response data is then processed and printed to the Output.
Test this script by pasting the source code into a Script (HttpService cannot be used by LocalScripts). Also, be sure to enable HTTP Requests in your Game Settings (Home > Game Settings).
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Make the request to our endpoint URL
local response = HttpService:GetAsync(URL_ASTROS)
-- Parse the JSON response
local data = HttpService:JSONDecode(response)
-- Information in the data table is dependent on the response 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.
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).
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)
Tóm Tắt
Thuộc Tính
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
Tạo một chuỗi ngẫu nhiên UUID/GUID, có thể có dấu ngoặc tròn.
Trả về một Secret từ cửa hàng bí mật.
Giải mã một chuỗi JSON thành một bảng Luau.
Tạo một chuỗi JSON từ một bảng Luau.
Thay thế các ký tự không an toàn URL bằng '%' và hai ký tự hexadecimal.
Gửi một yêu cầu HTTP GET .
- PostAsync(url : Variant,data : string,content_type : Enum.HttpContentType,compress : boolean,headers : Variant):string
Gửi một yêu cầu HTTP POST .
Gửi một yêu cầu HTTP bằng bất kỳ phương pháp HTTP nào cung cấp một từ điển thông tin.
Thuộc Tính
HttpEnabled
Khi được đặt thành true , cho phép các tập lệnh gửi yêu cầu đến các trang web bằng cách sử dụng HttpService:GetAsync() , HttpService:PostAsync() , và HttpService:RequestAsync() .
Thuộc tính này phải được bật/tắt thông qua giao diện Cài đặt trò chơi trong Studio, hoặc cho kinh nghiệm chưa công bố bằng cách đặt thuộc tính này thành bằng Command Bar :
game:GetService("HttpService").HttpEnabled = true
Phương Pháp
GenerateGUID
Phương pháp này tạo ra một chuỗi nhận dạng ngẫu nhiên và duy nhất toàn cầu ( UUID ) ngẫu nhiên.Sáu mươi sáu octet của một UUID được biểu diễn như 32 chữ số hexadecimal (cơ sở 16) được hiển thị trong năm nhóm được tách bởi dấu gạch ngang trong hình thức 8-4-4-4-12 với tổng cộng 36 ký tự, ví dụ 123e4567-e89b-12d3-a456-426655440000 .
Thông số UUID được sử dụng là Phiên bản 4 (ngẫu nhiên), biến thể 1 (DCE 1.1, ISO/IEC 11578:1996).UUID của phiên bản này được sử dụng phổ biến nhất do sự đơn giản của chúng, vì chúng được tạo ngẫu nhiên hoàn toàn.Lưu ý rằng phiên bản này không có các tính năng nhất định mà các phiên bản UUID khác có, chẳng hạn như dấu thời gian mã hóa, địa chỉ MAC hoặc sắp xếp theo thời gian như UUIDv7 hoặc ULID.
Có hơn 5.3×10 36 UUID v4 độc đáo, trong đó khả năng tìm thấy một phiên bản trùng lặp trong 103 triệu UUID là một trong một tỷ.
Tham số wrapInCurlyBraces xác định xem chuỗi trả về có được bọc trong dấu ngoặc kép ( {} ) hay không. Ví ví dụ / trường hợp:
- true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
- false : db454790-7563-44ed-ab4b-397ff5df737b
Tham Số
Liệu chuỗi trả về có nên được bọc trong dấu ngoặc kép ( {} ).
Lợi Nhuận
UUID ngẫu nhiên được tạo.
Mẫu mã
This example uses HttpService's GenerateGUID method to generate and print a universally unique identifier.
local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}
GetSecret
Phương pháp này trả về một giá trị đã được thêm vào cửa hàng bí mật trước đó cho trải nghiệm.Nội dung bí mật không thể in được và không có sẵn khi trải nghiệm chạy địa phương.
Các tham số trả về Secret có thể được biến đổi bằng cách sử dụng các phương pháp tích hợp sẵn như Secret:AddPrefix() . Nó được mong đợi được gửi như một phần của yêu cầu HTTP.
Để biết thêm thông tin, xem hướng dẫn sử dụng .
Tham Số
Lợi Nhuận
JSONDecode
Phương pháp này biến một đối tượng JSON hoặc mảng thành một bảng Luau với các tính năng sau:
- Các chìa khóa của bảng là chuỗi hoặc số nhưng không cả hai. Nếu một đối tượng JSON chứa cả hai, các chìa khóa dây sẽ bị bỏ qua.
- Một đối tượng JSON trống tạo ra một bảng Luau trống ( {} ).
- Nếu chuỗi input không phải là một đối tượng JSON hợp lệ, phương pháp này sẽ ném lỗi.
Để mã hóa một bảng Luau thành một đối tượng JSON, hãy sử dụng phương pháp HttpService:JSONEncode().
Phương pháp này có thể được sử dụng bất kể liệu yêu cầu HTTP có được bật hay không.
Tham Số
Vật thể JSON đang được giải mã.
Lợi Nhuận
Vật thể JSON giải mã như một bảng Luau.
Mẫu mã
This code sample gives an example JSON format string and parses it using HttpService's JSONDecode. It then verifies that the JSON was parsed correctly, and prints out some of the information within the object.
Try editing the JSON string to experiment with the format. Also experiment with inspecting the data in Lua to get comfortable with the Lua representation of the data (tables and other values).
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
Phương pháp này biến một bảng Luau thành một đối tượng JSON hoặc một mảng dựa trên các hướng dẫn sau:
Các chìa khóa của bảng phải là chuỗi hoặc số. Nếu bảng có cả hai, một mảng được ưu tiên (chìa khóa chuỗi bị bỏ qua).
Một bảng Luau trống ( {} ) tạo một mảng JSON trống.
Giá trị nil không bao giờ được tạo ra.
Tham chiếu bảng lặp gây ra một lỗi.
Phương pháp này cho phép các giá trị như inf và nan không phải là JSON hợp lệ.Điều này có thể gây ra vấn đề nếu bạn muốn sử dụng JSON xuất ở nơi khác.
Để đảo ngược quá trình mã hóa và giải mã một đối tượng JSON, hãy sử dụng phương pháp HttpService:JSONDecode().
Phương pháp này có thể được sử dụng bất kể liệu yêu cầu HTTP có được bật hay không.
Tham Số
Bảng nhập Luau.
Lợi Nhuận
Chuỗi JSON chuỗitrả về.
Mẫu mã
This code sample turns a Lua table tab into a JSON string using HttpService's JSONEncode. Then, it prints out the string.
Try editing the Lua table to see how the JSON output changes.
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
Phương pháp này mã hóa phần trăm một chuỗi nhất định để các ký tự dự trữ được mã hóa đúng cách với % và hai ký tự hexadecimal.
Điều này hữu ích khi định dạng URL để sử dụng với HttpService:GetAsync() / HttpService:PostAsync() , hoặc POST dữ liệu của loại phương tiện application/x-www-form-urlencoded ( Enum.HttpContentType.ApplicationUrlEncoded ).
Ví ví dụ / trường hợp, khi bạn mã hóa URL https://www.roblox.com/discover#/, phương pháp này trả về https%3A%2F%2Fwww%2Eroblox%2Ecom%2Fdiscover%23%2F .
Tham Số
Chuỗi (URL) để mã hóa.
Lợi Nhuận
chuỗiđã mã hóa.
Mẫu mã
This code sample uses UrlEncode to turn a string into a safe, percent-encoded string that can be used in a URL as an argument. Notice how only unreserved characters (letters, numbers and -_.~) are not transformed into percent-encoded equivalents. Characters with accents are also transformed (for example é is transformed into %C3).
local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- French for "I went to the movies"
local result = HttpService:UrlEncode(content)
print(result) --> Je%20suis%20all%C3%A9%20au%20cinema%2E
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).
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
Phương pháp này gửi một yêu cầu HTTP GET .Nó hoạt động tương tự như RequestAsync() ngoại trừ việc nó chấp nhận các tham số yêu cầu HTTP như tham số phương thức thay vì một từ điển duy nhất và trả về chỉ cơ thể của phản hồi HTTP.Nói chung, phương pháp này chỉ hữu ích như một tắt và RequestAsync() nên được sử dụng trong hầu hết các trường hợp.
Khi true , tham số nocache ngăn chặn phương pháp này lưu trữ kết quả lưu trữ từ các cuộc gọi trước với cùng url .
Tham Số
Địa chỉ web bạn yêu cầu dữ liệu từ.
Liệu yêu cầu có lưu trữ (lưu trữ) phản hồi hay không.
Dùng để xác định một số tiêu đề yêu cầu HTTP.
Lợi Nhuận
Thân phản hồi yêu cầu GET.
Mẫu mã
This code sample uses HttpService's GetAsync to make a request to Open Notify, a web service that provides data from NASA. The request is made to an endpoint that provides information on how many astronauts are currently in space. The response is provided in JSON format, so it is parsed using JSONDecode. Finally, the response data is then processed and printed to the Output.
Test this script by pasting the source code into a Script (HttpService cannot be used by LocalScripts). Also, be sure to enable HTTP Requests in your Game Settings (Home > Game Settings).
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Make the request to our endpoint URL
local response = HttpService:GetAsync(URL_ASTROS)
-- Parse the JSON response
local data = HttpService:JSONDecode(response)
-- Information in the data table is dependent on the response 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.
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
Phương pháp này gửi một yêu cầu HTTP POST .Nó hoạt động tương tự như RequestAsync() ngoại trừ việc nó chấp nhận các tham số yêu cầu HTTP như tham số phương thức thay vì một từ điển duy nhất và trả về chỉ cơ thể của phản hồi HTTP.Nói chung, phương pháp này chỉ hữu ích như một tắt và RequestAsync() nên được sử dụng trong hầu hết các trường hợp.
Khi true , tham số compress kiểm soát xem các thân yêu cầu lớn có bị nén bằng gzip hay không.
Tham Số
Địa chỉ đích cho dữ liệu.
Dữ liệu đang được khoản
Thay đổi giá trị trong đầu mục Content-Type được gửi theo yêu cầu.
Xác định xem dữ liệu có bị nén ( bị nén ) khi gửi hay không.
Dùng để xác định một số tiêu đề yêu cầu HTTP.
Lợi Nhuận
Phản hồi HTTP được gửi lại chỉ ra kết quả yêu cầu.
Mẫu mã
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).
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
Phương pháp này gửi một yêu cầu HTTP bằng một từ điển để xác định dữ liệu yêu cầu, chẳng hạn như URL mục tiêu, phương pháp, tiêu đề và dữ liệu cơ thể yêu cầu.Nó trả về một từ điển mô tả dữ liệu phản hồi đã nhận.Tùy chọn, yêu cầu có thể được nén bằng cách sử dụng Enum.HttpCompression .
Yêu cầu các trường từ điển
<th>Loại</th><th>Yêu cầu</th><th>Mô tả</th></tr></thead><tbody><tr><td><code>Liên kết</code></td><td>Chuỗi</td><td>có</td><td>URL mục tiêu cho yêu cầu này. Phải sử dụng <code>http</code> hoặc <code>https</code> giao thức.</td></tr><tr><td><code>Phương pháp</code></td><td>Chuỗi</td><td>no</td><td>Phương pháp HTTP được sử dụng bởi yêu cầu này, hầu hết là <code>Nhận</code> hoặc <code>Gửi</code>.</td></tr><tr><td><code>Tiêu đề</code></td><td>Từ điển</td><td>no</td><td>Một từ điển các tiêu đề sẽ được sử dụng với yêu cầu này. Hầu hết các tiêu đề HTTP được chấp nhận ở đây, nhưng không phải tất cả.</td></tr><tr><td><code>Thân</code></td><td>Chuỗi</td><td>no</td><td>Thân yêu thân.Có thể là bất kỳ chuỗi nào, bao gồm cả dữ liệu nhị phân.Phải bị loại bỏ khi sử dụng các phương pháp <code>Nhận</code> hoặc <code>Đầu</code> HTTP GET.Có thể cần phải xác định tiêu đề <code>Loại nội dung</code> khi gửi JSON hoặc các định dạng khác khi gửi JSON.</td></tr><tr><td><code>Ngăn xếp</code></td><td><code>Enum.HttpCompression Trang chủ</code></td><td>no</td><td>Một trường nén tùy chọn sẽ nén dữ liệu trong yêu cầu.Giá trị có thể là <code>Enum.HttpCompression.None</code> hoặc <code>Enum.HttpCompression.Gzip</code>.</td></tr></tbody>
Tên |
---|
Hỗ trợ các phương pháp HTTP
Các phương thức yêu cầu HTTP xác định mục đích của yêu cầu được thực hiện và những gì mong đợi nếu yêu cầu thành công.ví dụ / trường hợp, phương pháp yêu cầu GET cho thấy server tại địa chỉ yêu cầu rằng một tài nguyên đang được yêu cầu và, nếu thành công, tài nguyên tại địa chỉ đó sẽ được trả lại.Tương tự, phương pháp yêu cầu HEAD như vậy cũng làm tương tự ngoại trừ máy chủ biết trả lời không có thành phần Body .
<th>Mô tả</th><th>An toàn</th></tr></thead><tbody><tr><td><code>NHẬN</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/GET">ⓘ</a></td><td>Phương pháp <code>Nhận</code> yêu cầu tài nguyên tại địa chỉ được chỉ định. Không hỗ trợ sử dụng tham số <code>Thân</code>.</td><td>Có</td></tr><tr><td><code>ĐẦU</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/HEAD">ⓘ</a></td><td>Phương pháp <code>HEAD</code> yêu cầu một phản hồi tương tự như một yêu cầu <code>GET</code>, nhưng không có cơ thânphản hồi.Không hỗ trợ sử dụng tham số <code>Body</code>.</td><td>Có</td></tr><tr><td><code>GỬI</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/POST">ⓘ</a></td><td>Phương pháp <code>GỬI</code> đưa dữ liệu <code>Thân</code> được cung cấp đến địa chỉ yêu cầu.</td><td>No</td></tr><tr><td><code>Đặt</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PUT">ⓘ</a></td><td>Phương pháp <code>PUT</code> thay thế tất cả các lần lặp hiện tại của tài nguyên được đặc trưng trong dữ liệu <code>Body</code> cung cấp.</td><td>No</td></tr><tr><td><code>XÓA</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/DELETE">ⓘ</a></td><td>Phương pháp <code>XÓA</code> xóa tài nguyên được chỉ định trong dữ liệu <code>Thân</code> được cung cấp tại địa chỉ yêu cầu.</td><td>No</td></tr><tr><td><code>TÙY CHỌN</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/OPTIONS">ⓘ</a></td><td>Phương pháp <code>OPTIONS</code> yêu cầu các tùy chọn giao tiếp được phép cho địa chỉ cung cấp.</td><td>Có</td></tr><tr><td><code>TRACE</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/TRACE">ⓘ</a></td><td>Phương pháp <code>TRACE</code> thực hiện kiểm tra vòng lặp lời nhắn dọc theo con đường đến tài nguyên được chỉ định trong dữ liệu <code>Thân</code> được cung cấp.</td><td>Có</td></tr><tr><td><code>BẢN CẬP NHẬT</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PATCH">ⓘ</a></td><td>Phương pháp <code>SỬA LỖI</code> áp dụng các thay đổi một phần cho tài nguyên được chỉ định trong dữ liệu <code>Thân</code> được cung cấp tại địa chỉ yêu cầu.</td><td>No</td></tr></tbody>
Phương pháp |
---|
Đầu mối HTTP
Trong từ điển yêu cầu, bạn có thể xác định các tiêu đề HTTP tùy chỉnh để sử dụng trong yêu cầu.Tuy nhiên, một số tiêu đề không thể được xác định.Ví dụ, Content-Length được xác định từ thânthể yêu cầu.User-Agent và Roblox-Id bị khóa bởi Roblox.Các tiêu đề khác như Accept hoặc Cache-Control sử dụng các giá trị mặc định nhưng có thể bị thay thế.Phổ biến hơn, một số API REST có thể yêu cầu API key hoặc xác minh dịch vụ khác phải được định nghĩa trong tiêu đề yêu cầu.
Phương thức RequestAsync() không phát hiện định dạng nội dung thân.Nhiều máy chủ web yêu cầu tiêu đề Content-Type được đặt thích hợp khi gửi các định dạng nhất định. Các phương pháp khác của sử dụng enum ; cho phương pháp này thiết lập đầu mục thích hợp: , > , > , > hoặc > là các giá trị đầu mục thay thế cho các giá trị enum tương ứng.
Các trường từ điển phản hồi
RequestAsync() trả về một từ điển chứa các trường sau:
<th>Loại</th><th>Mô tả</th></tr></thead><tbody><tr><td><code>Thành công</code></td><td>Boolean Hoặc</td><td>Tình trạng thành công của yêu cầu. Điều này là đúng nếu và chỉ nếu <code>StatusCode</code> nằm trong phạm vi <code>200</code> - <code>299</code>.</td></tr><tr><td><code>Mã trạng thái</code></td><td>Số nguyên</td><td>Mã đáp lời HTTP xác định tình trạng của phản hồi.</td></tr><tr><td><code>Tin nhắn trạng thái</code></td><td>Chuỗi</td><td>Tin nhắn trạng thái đã được gửi quay lại.</td></tr><tr><td><code>Tiêu đề</code></td><td>Từ điển</td><td>Một từ điển các tiêu đề đã được đặt trong phản hồi này.</td></tr><tr><td><code>Thân</code></td><td /><td>Thân yêu cầu (nội dung) nhận được trong phản hồi.</td></tr></tbody>
Tên |
---|
Trường hợp lỗi
RequestAsync() nâng lên một lỗi nếu thời gian phản hồi hết hạn hoặc nếu máy chủ mục tiêu từ chối yêu cầu.Nếu một dịch vụ web bị gián đoạn vì một số lý do, nó có thể gây ra các kịch bản sử dụng phương pháp này ngừng hoạt động hoàn toàn.Thường là một ý tưởng tốt để bọc các cuộc gọi đến phương pháp này trong pcall() và xử lý lỗi một cách thanh lịch nếu thông tin cần thiết không có sẵn.
Hạn chế
Giới hạn hiện tại cho việc gửi và nhận yêu cầu HTTP là 500 yêu cầu mỗi phút.Yêu cầu vượt quá ngưỡng này sẽ thất bại.Ngoài ra, các tên miền Roblox bị loại trừ.Điều này có nghĩa là các yêu cầu HTTP không thể được gửi đến bất kỳ trang web thuộc sở hữu của Roblox như www.roblox.com.
Tham Số
Một từ điển chứa thông tin cần yêu cầu từ máy chủ được chỉ định.
Lợi Nhuận
Một từ điển chứa thông tin phản hồi từ máy chủ được chỉ định.
Mẫu mã
This code sample demonstrates sending a single HTTP POST request with JSON data to the website httpbin.org, a website that helps debug HTTP requests. Here, we send some JSON data by using HttpService:JSONEncode() and also setting the Content-Type header.
-- 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