HttpService
*Konten ini diterjemahkan menggunakan AI (Beta) dan mungkin mengandung kesalahan. Untuk melihat halaman ini dalam bahasa Inggris, klik di sini.
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.
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.
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.
- 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.
- Permintaan tidak dapat dibuat ke situs web Roblox mana pun, seperti www.roblox.com.
- 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 unityang 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
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)
Rangkuman
Properti
Menunjukkan apakah permintaan HTTP dapat dikirim ke situs web eksternal.
Metode
Membuat string acak UUID/GUID, opcional dengan kurungan gulungan.
Kembalikan Secret dari toko rahasia.
Memecahkan string JSON ke tabel Luau.
Hasilkan string JSON dari tabel Luau.
Mengganti karakter URL-tidak aman dengan '%' dan dua karakter heksadesimal.
Mengirim permintaan HTTP GET .
- PostAsync(url : Variant,data : string,content_type : Enum.HttpContentType,compress : boolean,headers : Variant):string
Mengirim permintaan HTTP POST .
Mengirim permintaan HTTP menggunakan metode HTTP apa pun yang diberikan kamus informasi.
Properti
HttpEnabled
Ketika diatur ke true , memungkinkan skrip untuk mengirim permintaan ke situs web menggunakan HttpService:GetAsync() , HttpService:PostAsync() , dan HttpService:RequestAsync() .
Properti ini harus diaktifkan melalui antarmuka Pengaturan Permainan di Studio, atau untuk pengalaman tidak dipublikasikan dengan mengatur properti ini ke true menggunakan Bilah Perintah :
game:GetService("HttpService").HttpEnabled = true
Metode
GenerateGUID
Metode ini menghasilkan string identifikasi universal unik acak (UIDD).Delapan belas bilibit dari UUID diwakili sebagai 32 bilibit hexadecimal (basis 16), ditampilkan dalam lima kelompok yang dipisahkan oleh hipen dalam bentuk 8-4-4-4-12 untuk total 36 karakter, misalnya 123e4567-e89b-12d3-a456-426655440000 .
Spesifikasi UUID yang digunakan adalah Versi 4 (acak) , varian 1 (DCE 1.1, ISO/IEC 11578:1996).UID versi ini paling banyak digunakan karena sederhana, karena sepenuhnya dihasilkan secara acak.Perhatikan bahwa versi ini tidak memiliki fitur tertentu yang dimiliki versi UUID lain, seperti stempel waktu yang dikodekan, alamat MAC, atau pengurutan berdasarkan waktu seperti UUIDv7 atau ULID.
Ada lebih dari 5.3×10 36 UUID unik v4, di mana probabilitas menemukan duplikat dalam 103 triliun UUID adalah satu dari satu miliar.
Argumen wrapInCurlyBraces menentukan apakah string yang dikembalikan dibungkus dalam kurungan melengkung ( {} ). kejadian:
- true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
- false : db454790-7563-44ed-ab4b-397ff5df737b
Parameter
Apakah string yang dikembalikan harus dibungkus dalam kurungan melengkung ( {} ).
Memberikan nilai
UID yang dihasilkan secara acak.
Contoh Kode
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
Metode ini men返回值 yang sebelumnya ditambahkan ke toko rahasia untuk pengalaman.Konten rahasia tidak dapat dicetak dan tidak tersedia saat pengalaman dijalankan secara lokal.
Kembali Secret dapat diubah menggunakan metode bawaan seperti Secret:AddPrefix() . Diharapkan dikirim sebagai bagian dari permintaan HTTP.
Untuk informasi lebih lanjut, lihat panduan penggunaan untuk.
Parameter
Memberikan nilai
JSONDecode
Metode ini mengubah objek JSON atau array menjadi tabel Luau dengan karakteristik berikut:
- Kunci dari tabel adalah string atau angka tetapi tidak keduanya. Jika objek JSON berisi keduanya, kunci string diabaikan.
- Objek JSON kosong menghasilkan tabel Luau kosong ( {} ).
- Jika string input tidak valid, metode ini akan menyebabkan kesalahan.
Untuk mengkodekan tabel Luau ke objek JSON, gunakan metode HttpService:JSONEncode().
Metode ini dapat digunakan terlepas dari apakah permintaan HTTP diaktifkan.
Parameter
Objek JSON yang didekodekan.
Memberikan nilai
Objek JSON yang didekode sebagai tabel Luau.
Contoh Kode
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
Metode ini mengubah tabel Luau menjadi objek JSON atau array berdasarkan pedoman berikut:
Kunci dari tabel harus menjadi string atau angka. Jika tabel berisi keduanya, array memiliki prioritas (kunci string diabaikan).
Meja Luau kosong ( {} ) menghasilkan array JSON kosong.
Nilai nil tidak pernah dihasilkan.
Referensi tabel berulang menyebabkan kesalahan.
Metode ini memungkinkan nilai seperti inf dan nan yang tidak valid JSON.Ini dapat menyebabkan masalah jika Anda ingin menggunakan JSON yang dihasilkan di tempat lain.
Untuk membalikkan proses enkode dan memecahkan objek JSON, gunakan metode HttpService:JSONDecode().
Metode ini dapat digunakan terlepas dari apakah permintaan HTTP diaktifkan.
Parameter
Tabel masuk Luau.
Memberikan nilai
stringJSON yang dikembalikan.
Contoh Kode
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
Metode ini persen-mengkodekan sebuah string tertentu sehingga karakter yang disediakan dikodekan dengan benar dengan % dan dua karakter heksadesimal.
Ini berguna ketika memformat URL untuk digunakan dengan HttpService:GetAsync() / HttpService:PostAsync() , atau POST data jenis media application/x-www-form-urlencoded ( Enum.HttpContentType.ApplicationUrlEncoded ).
Sebagai kejadian, ketika Anda mengkodekan URL https://www.roblox.com/discover#/, metode ini men返回 https%3A%2F%2Fwww%2Eroblox%2Ecom%2Fdiscover%23%2F .
Parameter
String (URL) untuk dienkodekan.
Memberikan nilai
stringyang dienkode.
Contoh Kode
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
Metode ini mengirim permintaan HTTP GET .Ini berfungsi serupa dengan RequestAsync() kecuali bahwa ia menerima parameter permintaan HTTP sebagai parameter metode bukan hanya satu kamus dan hanya mengembalikan tubuh respons HTTP.Secara umum, metode ini hanya berguna sebagai singkatan dan RequestAsync() harus digunakan dalam kebanyakan kasus.
Ketika true , parameter nocache mencegah metode ini menyimpan hasil penyimpanan dari panggilan sebelumnya dengan url yang sama.
Parameter
Alamat web dari mana Anda meminta data.
Apakah permintaan menyimpan (cache) respons.
Digunakan untuk menentukan beberapa header permintaan HTTP.
Memberikan nilai
Tubuh respons permintaan GET.
Contoh Kode
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
Metode ini mengirim permintaan HTTP POST .Ini berfungsi serupa dengan RequestAsync() kecuali bahwa ia menerima parameter permintaan HTTP sebagai parameter metode bukan hanya satu kamus dan hanya mengembalikan tubuh respons HTTP.Secara umum, metode ini hanya berguna sebagai singkatan dan RequestAsync() harus digunakan dalam kebanyakan kasus.
Ketika true , parameter compress mengontrol apakah tubuh permintaan besar akan dikompresi menggunakan gzip .
Parameter
Alamat tujuan untuk data.
Data yang dikirim.
Mengubah nilai di header Content-Type yang dikirim dengan permintaan.
Menentukan apakah data dikompresi ( dikompresi ) saat dikirim.
Digunakan untuk menentukan beberapa header permintaan HTTP.
Memberikan nilai
Respons HTTP yang dikirim kembali menunjukkan hasil permintaan.
Contoh Kode
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
Metode ini mengirim permintaan HTTP menggunakan kamus untuk menentukan data permintaan, seperti URL target, metode, header, dan data tubuh permintaan.Ini mengembalikan kamus yang menggambarkan data respons yang diterima.Opsi, permintaan dapat dikompresi menggunakan Enum.HttpCompression .
Permintaan bidang kamus
<th>Jenis</th><th>Diperlukan</th><th>Deskripsi</th></tr></thead><tbody><tr><td><code>Url</code></td><td>Tali</td><td>tidak</td><td>URL target untuk permintaan ini. Harus menggunakan <code>http</code> atau <code>https</code> protokol.</td></tr><tr><td><code>Metode</code></td><td>Tali</td><td>no</td><td>Metode HTTP yang digunakan oleh permintaan ini, paling sering <code>MENDAPATKAN</code> atau <code>MENGIRIM</code>.</td></tr><tr><td><code>Kepala</code></td><td>Kamus</td><td>no</td><td>Kamus judul yang akan digunakan dengan permintaan ini. Kebanyakan HTTP header diterima di sini, tetapi tidak semua.</td></tr><tr><td><code>Tubuh</code></td><td>Tali</td><td>no</td><td>Tubuh tubuh.Dapat menjadi string apa pun, termasuk data binari.Harus dikecualikan saat menggunakan metode <code>GET</code> atau <code>HEAD</code> HTTP.Mungkin perlu untuk menyebutkan kepala <code>Tipe Konten</code> saat mengirim JSON atau format lainnya.</td></tr><tr><td><code>Mengekompresi</code></td><td><code>Enum.HttpKompresi HTTP</code></td><td>no</td><td>Bidang kompresi opsional yang akan mengompresi data dalam permintaan.Nilainya bisa menjadi <code>Enum.HttpCompression.None</code> atau <code>Enum.HttpCompression.Gzip</code>.</td></tr></tbody>
Nama |
---|
Metode HTTP yang didukung
Metode permintaan HTTP menentukan tujuan permintaan yang dilakukan dan apa yang diharapkan jika permintaan berhasil.Sebagai kejadian, metode permintaan GET memberi tahu server di alamat yang diminta bahwa sumber daya yang diminta dan, jika berhasil, sumber daya di alamat itu akan dikembalikan.Demikian pula, metode permintaan HEAD melakukan hal yang sama kecuali server tahu untuk mengembalikan respons tanpa elemen Body.
<th>Deskripsi</th><th>Amankah</th></tr></thead><tbody><tr><td><code>DAPATKAN</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/GET">ⓘ</a></td><td>Metode <code>Dapatkan</code> meminta sumber daya di alamat yang ditentukan. Tidak mendukung penggunaan parameter <code>Tubuh</code>.</td><td>Tidak</td></tr><tr><td><code>KEPALA</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/HEAD">ⓘ</a></td><td>Metode <code>HEAD</code> meminta respons yang identik dengan permintaan <code>GET</code>, tetapi tanpa tubuh respons.Tidak mendukung penggunaan parameter <code>Tubuh</code>.</td><td>Tidak</td></tr><tr><td><code>POST</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/POST">ⓘ</a></td><td>Metode <code>POST</code> mengirimkan data <code>Badan</code> yang disediakan ke alamat yang diminta.</td><td>No</td></tr><tr><td><code>PUT</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PUT">ⓘ</a></td><td>Metode <code>PUT</code> menggantikan semua iterasi saat ini dari sumber daya yang ditentukan dalam data <code>Tubuh</code> yang disediakan.</td><td>No</td></tr><tr><td><code>MENGHAPUS</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/DELETE">ⓘ</a></td><td>Metode <code>HAPUS</code> menghapus sumber daya yang ditentukan dalam data <code>Badan</code> yang disediakan di alamat yang diminta.</td><td>No</td></tr><tr><td><code>PILIHAN</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/OPTIONS">ⓘ</a></td><td>Metode <code>PILIHAN</code> meminta opsi komunikasi yang diizinkan untuk alamat yang disediakan.</td><td>Tidak</td></tr><tr><td><code>MENGUJI</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/TRACE">ⓘ</a></td><td>Metode <code>TRACE</code> melakukan tes loop balik pesan di sepanjang jalur ke sumber daya yang ditentukan dalam data <code>Tubuh</code> yang disediakan.</td><td>Tidak</td></tr><tr><td><code>PERBAIKAN</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PATCH">ⓘ</a></td><td>Metode <code>PATCH</code> menerapkan perubahan parsial pada sumber daya yang ditentukan dalam data <code>Body</code> yang disediakan di alamat yang diminta.</td><td>No</td></tr></tbody>
Metode |
---|
Kepala HTTP
Di kamus permintaan, Anda dapat menentukan header HTTP khusus untuk digunakan dalam permintaan.Namun, beberapa judul tidak dapat ditentukan.Sebagai contoh, Content-Length ditentukan dari tubuh permintaan.User-Agent dan Roblox-Id dikunci oleh Roblox.Header lain seperti Accept atau Cache-Control menggunakan nilai default tetapi dapat dihapus.Lebih umum, beberapa API REST mungkin memerlukan kunci API atau autentikasi layanan lainnya untuk disebutkan dalam header permintaan.
Metode RequestAsync() tidak mendeteksi format konten tubuh.Banyak server web memerlukan header Content-Type diatur sesuai ketika mengirim format tertentu.Metode lain dari menggunakan enum; untuk metode ini atur header yang sesuai: , , , atau adalah nilai header pengganti untuk nilai enum masing-masing.
Bidang kamus respons
RequestAsync() kembali kamus yang berisi bidang berikut:
<th>Jenis</th><th>Deskripsi</th></tr></thead><tbody><tr><td><code>Keberhasilan</code></td><td>Boolean</td><td>Status keberhasilan permintaan. Ini benar jika dan hanya jika <code>StatusCode</code> berada dalam rentang <code>200</code> - <code>299</code>.</td></tr><tr><td><code>Kode Status</code></td><td>Angka bulat</td><td>Kode respons HTTP yang mengidentifikasi status respons.</td></tr><tr><td><code>Pesan Status</code></td><td>Tali</td><td>Pesan status yang dikembalikan.</td></tr><tr><td><code>Kepala</code></td><td>Kamus</td><td>Kamus judul yang ditetapkan dalam respons ini.</td></tr><tr><td><code>Tubuh</code></td><td /><td>Tubuh permintaan (isi) yang diterima dalam respons.</td></tr></tbody>
Nama |
---|
Kasus Kesalahan
RequestAsync() menimbulkan kesalahan jika waktu respons berakhir atau jika server target menolak permintaan.Jika layanan web turun karena beberapa alasan, itu dapat menyebabkan skrip yang menggunakan metode ini berhenti berfungsi sama sekali.Seringkali merupakan ide bagus untuk melapisi panggilan ke metode ini di pcall() dan dengan sopan menangani kasus kegagalan jika informasi yang diperlukan tidak tersedia.
Keterbatasan
Batasan saat ini untuk mengirim dan menerima permintaan HTTP adalah 500 permintaan per menit.Permintaan di atas ambang batas ini akan gagal.Selain itu, domain Roblox dikecualikan.Ini berarti bahwa permintaan HTTP tidak dapat dikirim ke situs milik Roblox seperti www.roblox.com.
Parameter
Kamus yang berisi informasi yang diminta dari server yang ditentukan.
Memberikan nilai
Kamus yang berisi informasi respons dari server yang ditentukan.
Contoh Kode
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