HttpService

Tampilkan yang Tidak Digunakan Lagi

*Konten ini diterjemahkan menggunakan AI (Beta) dan mungkin mengandung kesalahan. Untuk melihat halaman ini dalam bahasa Inggris, klik di sini.

Tidak Dapat Dibuat
Layanan

HttpService memungkinkan permintaan HTTP dikirim dari server game menggunakan RequestAsync , GetAsync dan PostAsync .Layanan ini memungkinkan game untuk disatukan dengan layanan web off-Roblox seperti analitik, penyimpanan data, konfigurasi server jarak jauh, pelaporan kesalahan, perhitungan lanjutan atau komunikasi waktu nyata.Selain itu, beberapa API web Roblox juga dapat diakses melalui HttpService (lihat di bawah).

HttpService juga menyediakan metode JSONEncode dan JSONDecode yang berguna untuk berkomunikasi dengan layanan yang menggunakan format JSON .Selain itu, metode GenerateGUID memberikan label acak 128-bit yang dapat diperlakukan sebagai unik secara probabilistik dalam berbagai skenario.

Anda hanya harus mengirim permintaan HTTP ke platform pihak ketiga tepercaya untuk menghindari membuat pengalaman Anda rentan terhadap risiko keamanan.

Properti ini tidak dapat berinteraksi dengan saat runtime.

Aktifkan permintaan HTTP

Metode pengiriman permintaan tidak diaktifkan secara default. Untuk mengirim permintaan, Anda harus mengaktifkan permintaan HTTP untuk pengalaman Anda.

Gunakan di plugin

HttpService dapat digunakan oleh plugin Studio.Mereka mungkin melakukan ini untuk memeriksa pembaruan, mengirim data penggunaan, mengunduh konten, atau logika bisnis lainnya.Pertama kali plugin mencoba melakukan ini, pengguna mungkin diminta untuk memberikan izin kepada plugin untuk berkomunikasi dengan alamat web tertentu.Pengguna dapat menerima, menolak, dan menarik kembali izin seperti itu kapan saja melalui jendela Manajemen Plugin .

Plugin juga dapat berkomunikasi dengan perangkat lunak lain yang berjalan di komputer yang sama melalui host localhost dan 127.0.0.1.Dengan menjalankan program yang kompatibel dengan plugin semacam itu, Anda dapat memperluas fungsionalitas plugin Anda di luar kemampuan normal Studio, seperti berinteraksi dengan sistem file komputer Anda.Waspadalah bahwa perangkat lunak semacam itu harus didistribusikan secara terpisah dari plugin itu sendiri dan dapat menimbulkan bahaya keamanan jika Anda tidak berhati-hati.

Memanggil domain Roblox

HttpService saat ini hanya dapat memanggil subset dari akhiran Open Cloud.Kami berencana untuk memperluas set ini seiring waktu jadi silakan gunakan tombol Umpan Balik jika Anda memiliki titik akhir khusus yang ingin Anda lihat:

Grup
Penyimpan Data

Karena batasan saat ini pada HttpService , hanya karakter alfanumerik dan karakter - diizinkan dalam parameter jalur URL ke domain Roblox.Ini berarti Toko Data/entri dengan karakter khusus lainnya saat ini tidak dapat diakses dari HttpService .

Barang Inventaris
Toko Pencipta

Anda dapat memanggil titik akhir ini dengan cara yang sama seperti Anda memanggil titik akhir lain melalui HttpService.Satu-satunya perbedaan adalah Anda harus menyertakan kunci API Cloud Terbuka dalam permintaan:

  1. Buat permintaan (contoh kode di bawah ini).

Keterbatasan termasuk hal berikut:

  • Hanya kepala x-api-key dan content-type yang diizinkan.
  • Header x-api-key harus menjadi Secret.
  • Hanya karakter alfanumerik dan karakter - diizinkan dalam parameter jalur URL.
  • Hanya protokol https:// yang didukung.
Pembatasan Tingkat

Untuk setiap server game Roblox, ada batas 500 permintaan HTTP per menit.Melebihi ini dapat menyebabkan metode pengiriman permintaan mogok sepenuhnya selama sekitar 30 detik.Layanan Anda pcall() mungkin juga gagal dengan pesan "Number of requests exceeded limit."

  • Permintaan Cloud Terbuka mengkonsumsi batas umum yang sama dari 500 permintaan HTTP per menit yang diterapkan pada semua permintaan lainnya.

  • Setiap ujung cloud terbuka memiliki batas sendiri per pemilik kunci API (dapat menjadi pengguna atau kelompok) yang diterapkan tidak peduli dari mana asal panggilan ( HttpService , web, dll.).Header berikut dikembalikan dengan setiap respons dan memungkinkan Anda untuk melihat batas dan kuota tersisa:

    • x-ratelimit-limit - Jumlah total permintaan yang diizinkan dibuat per pemilik kunci API (biasanya per menit).
    • x-ratelimit-remaining - Jumlah permintaan yang digunakan kunci API masih diizinkan untuk dibuat.Jika angka ini adalah 0 dan Anda menerima kode status respons HTTP 429, maka Anda telah mencapai batas tingkat untuk endpoint ini.
    • x-ratelimit-reset - Jumlah detik yang tersisa sebelum batas tingkat diatur ulang (yaitu sebelum x-ratelimit-remaining diubah menjadi x-ratelimit-limit ).
Pertimbangan tambahan
  • Ada batasan pelabuhan.Anda tidak dapat menggunakan port 1194 atau port di bawah 1024 , kecuali 80 dan 443.Jika Anda mencoba menggunakan port yang diblokir, Anda akan menerima kesalahan 403 Forbidden atau ERR_ACCESS_DENIED.
  • Permintaan web dapat gagal karena banyak alasan, jadi penting untuk "membuat kode defensif" (menggunakan pcall()) dan memiliki rencana ketika permintaan gagal.
  • Meskipun protokol http:// di dukung, Anda harus menggunakan https:// di mana pun mungkin.
  • Permintaan yang dikirim harus memberikan bentuk autentikasi yang aman, seperti kunci rahasia yang dipersiapkan sebelumnya, sehingga aktor jahat tidak dapat berpura-pura menjadi salah satu server game Roblox Anda.
  • Waspadalah terhadap kapasitas dan kebijakan batasan tingkat umum dari server web ke mana permintaan dikirim.

Contoh Kode

Contoh kode ini menggunakan HttpService's GetAsync untuk membuat permintaan ke Open Notify, sebuah layanan web yang menyediakan data dari NASA.Permintaan dibuat ke akhiran yang memberikan informasi tentang berapa banyak astronot saat ini berada di luar angkasa.Respon disediakan dalam format JSON, sehingga dapat diuraikan menggunakan JSONDecode.Akhirnya, data respons kemudian diproses dan dicetak ke Output.

Uji skrip ini dengan menempelkan kode sumber ke Skrip (HttpService tidak dapat digunakan oleh LocalScripts).Juga, pastikan untuk mengaktifkan Permintaan HTTP di Pengaturan Game Anda (Rumah > Pengaturan Game).

Para Astronot di Luar Angkasa

local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Buat permintaan ke URL endpoint kami
local response = HttpService:GetAsync(URL_ASTROS)
-- Memproses respons JSON
local data = HttpService:JSONDecode(response)
-- Informasi di tabel data tergantung pada respons 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

Rangkuman

Properti

  • Keamanan Pengguna Lokal
    Baca Paralel

    Menunjukkan apakah permintaan HTTP dapat dikirim ke situs web eksternal.

Metode

Properti

HttpEnabled

Keamanan Pengguna Lokal
Baca Paralel

Metode

GenerateGUID

Tulis Paralel

Parameter

wrapInCurlyBraces: boolean
Nilai Default: true

Memberikan nilai

Contoh Kode

HttpService GenerateGUID

local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}

GetSecret

Tulis Paralel

Parameter

key: string
Nilai Default: ""

Memberikan nilai

JSONDecode

Variant
Tulis Paralel

Parameter

input: string
Nilai Default: ""

Memberikan nilai

Variant

Contoh Kode

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

Tulis Paralel

Parameter

input: Variant
Nilai Default: ""

Memberikan nilai

Contoh Kode

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

Tulis Paralel

Parameter

input: string
Nilai Default: ""

Memberikan nilai

Contoh Kode

HttpService UrlEncode

local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- Prancis untuk "Saya pergi ke bioskop"
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

Hasil

Parameter

url: Variant
Nilai Default: ""
nocache: boolean
Nilai Default: false
headers: Variant
Nilai Default: ""

Memberikan nilai

Contoh Kode

Para Astronot di Luar Angkasa

local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Buat permintaan ke URL endpoint kami
local response = HttpService:GetAsync(URL_ASTROS)
-- Memproses respons JSON
local data = HttpService:JSONDecode(response)
-- Informasi di tabel data tergantung pada respons 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

Hasil

Parameter

url: Variant
Nilai Default: ""
data: string
Nilai Default: ""
content_type: Enum.HttpContentType
Nilai Default: "ApplicationJson"
compress: boolean
Nilai Default: false
headers: Variant
Nilai Default: ""

Memberikan nilai

Contoh Kode

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

Hasil

Parameter

requestOptions: Dictionary
Nilai Default: ""

Memberikan nilai

Contoh Kode

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

Acara