HttpService
*Bu içerik, yapay zekâ (beta) kullanılarak çevrildi ve hatalar içerebilir. Sayfayı İngilizce görüntülemek için buraya tıkla.
HttpService HTTP isteklerinin RequestAsync , GetAsync ve PostAsync kullanarak oyun sunucularından gönderilmesine izin verir.Bu hizmet, oyunların analiz, veri depolama, uzak sunucu yapılandırması, hata bildirimi, gelişmiş hesaplamalar veya gerçek zamanlı iletişim gibi off-Roblox web hizmetleriyle entegre edilmesine izin verir.
HttpService ayrıca JSONEncode ve JSONDecode servislerle iletişim kurmak için kullanışlı olan JSON formatını kullanan yöntemleri de barındırır.Ayrıca, GenerateGUID yöntemi çeşitli senaryolarda olasılıkla benzersiz olarak ele alınabilen rastgele 128-bit etiketler sağlar.
Deneyiminizi güvenlik risklerine açık hale getirmekten kaçınmak için yalnızca güvenilir üçüncü taraf platformlara HTTP isteği göndermelisiniz.
Bu özellik çalışma sırasında etkileştirilemez.
HTTP isteklerini etkinleştir
İstek gönderme yöntemleri varsayılan olarak etkinleştirilmez. İstek göndermek için, deneyiminiz için HTTP isteklerini etkinleştirmeniz gerekir.
Plug-inlerde kullanım
HttpService Stüdyo eklentileri tarafından kullanılabilir.Güncelleme kontrol etmek, kullanım verileri göndermek, içerik indirmek veya diğer iş mantığı yapmak için bunu yapabilirler.Bir eklenti ilk kez bunu yapmaya çalıştığında, kullanıcıya belirli web adresi ile iletişim kurma izni verilmesi istenebilir.Bir kullanıcı, bu izinleri herhangi bir zamanda Eklenti Yönetimi penceresi aracılığıyla kabul edebilir, reddedebilir ve geri alabilir.
Eklentiler ayrıca aynı bilgisayarda çalışan diğer yazılımlarla iletişim kurabilir localhost ve 127.0.0.1 hostları aracılığıyla.Bu tür eklentilerle uyumlu programları çalıştırarak, eklentinizin işlevini normal Studio yeteneklerinin ötesine genişletebilirsiniz, örneğin bilgisayarınızın dosya sistemiyle etkileşim kurmak.Bu tür yazılımların kendi pluginden ayrı olarak dağıtılması gerektiğine ve dikkat etmezseniz güvenlik tehlikeleri oluşturabileceğine dikkat edin.
Ek düşünceler
- Liman kısıtlamaları var.Port 1194 veya 1024 altındaki herhangi bir port kullanamazsınız, 80 ve 443 dışında.Engellenmiş bir port kullanmaya çalışırsanız, bir 403 Forbidden veya ERR_ACCESS_DENIED hatası alırsınız.
- Her Roblox oyun sunucusu için, dakika başına 500 HTTP isteği sınırı vardır.Bunu aşmak, istek gönderme yöntemlerinin yaklaşık 30 saniye boyunca tümüyle durmasına neden olabilir.
- Talepler www.roblox.com gibi herhangi bir Roblox web sitesine yapılamaz.
- Web istekleri birçok nedenden dolayı başarısız olabilir, bu nedenle "savunma kodu" kullanmak (pcall()) ve istekler başarısız olduğunda bir plan yapmak önemlidir.
- http:// protokolü desteklenmesine rağmen, mümkün olduğunca https:// kullanmalısınız.
- Gönderilen istekler, önceden paylaşılan gizli bir anahtar gibi güvenli bir doğrulama yöntemi sağlamalıdır, böylece kötü aktörler Roblox oyun sunucularınızdan biri olarak görünebilir.
- Taleplerin gönderildiği web sunucularının genel kapasite ve oran sınırlama politikalarının farkında olun.
Kod Örnekleri
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)
Özet
Özellikler
HTTP isteklerinin dış web sitelerine gönderilebileceğini belirtir.
Yöntemler
Seçmeli olarak kıvrımlı parantezlerle birlikte rastgele bir UUID/GUID diziüretir.
Gizli depolardan bir Secret döndürür.
Bir JSON dizesini Luau tablosuna çözümler.
Luau tablosundan bir JSON dize oluştur.
URL-güvensiz karakterleri:% ve iki onaltı karakter ile değiştirir.
Bir HTTP talepgönderir.
- PostAsync(url : Variant,data : string,content_type : Enum.HttpContentType,compress : boolean,headers : Variant):string
Bir HTTP talepgönderir.
Bir bilgi sözlüğü verilen herhangi bir HTTP yöntemi kullanarak bir HTTP isteği gönderir.
Özellikler
HttpEnabled
true olarak ayarlanırken, senaryoların HttpService:GetAsync() , HttpService:PostAsync() ve HttpService:RequestAsync() kullanarak web sitelerine istek göndermesine izin verir.
Bu özellik, Studio'daki Oyun Ayarları arayüzünde veya yayınlanmamış deneyimler için bu özelliği true kullanarak Komut Çubuğu üzerinden değiştirilmelidir:
game:GetService("HttpService").HttpEnabled = true
Yöntemler
GenerateGUID
Bu yöntem bir rastgele evrensel benzersiz tanımlayıcı üretir (UUID) dizi.Bir UUID'nin on altı biti, örneğin 36 karakter için şekilde 8-4-4-4-12 formunda virgüllerle ayrılmış beş grup olarak gösterilir, örneğin 123e4567-e89b-12d3-a456-426655440000 .
Kullanılan UUID özelliği Versiyon 4 (rastgele) , varyant 1 (DCE 1.1, ISO/IEC 11578:1996).Bu sürümün UUID'leri, basitliği nedeniyle en yaygın kullanılanlardır, çünkü tümü rastgele üretilmiştir.Bu sürümün, diğer UUID sürümlerinin sahip olduğu bazı özelliklere sahip olmadığını unutmayın, örneğin kodlanmış tarih damgaları, MAC adresleri veya UUIDv7 veya ULID gibi süre tabanlı sıralama.
103 trilyon UUID'de bir yinelenme bulma olasılığı bir milyarda bir olan 5.3×10 36 eşsiz v4 UUID'leri bulunmaktadır.
wrapInCurlyBraces argümanı, döndürülen dizeyi kıvrımlı parantezlerde sarıp sarımadığını belirler ({}). durum:
- true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
- false : db454790-7563-44ed-ab4b-397ff5df737b
Parametreler
Döndürülen dize kıvrık parantezlerde sarılmalı mı ( {} ).
Dönüşler
Rastgele oluşturulan UUID.
Kod Örnekleri
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
Bu yöntem, deneyim için daha önce gizli depolara eklenen bir değeri geri döndürür.Gizli içerik yazdırılamaz ve deneyim yerel olarak çalışırken mevcut değildir.
Geri döndürülen Secret , Secret:AddPrefix() gibi yerleşik yöntemler kullanılarak dönüştürülebilir. Bir HTTP talepbir parçası olarak gönderilmesi beklenir.
Daha fazla bilgi için, kullanım kılavuzuna bakın.
Parametreler
Dönüşler
JSONDecode
Bu yöntem, bir JSON nesnesini veya dizesini aşağıdaki özelliklerle bir Luau tablosuna dönüştürür:
- Tablonun anahtarları dize veya sayılardır, ancak her ikisi de değildir. Bir JSON nesnesi her ikisini de içeriyorsa, dize anahtarları göz ardı edilir.
- Boş bir JSON nesnesi boş bir Luau tablosu oluşturur ( {} ).
- input dize geçerli bir JSON nesnesi değilse, bu yöntem bir hata atar.
Bir Luau tablosunu JSON nesnesine dönüştürmek için, HttpService:JSONEncode() yöntemini kullanın.
Bu yöntem, HTTP isteklerinin etkinleştirilip etkinleştirilmediğine bakılmaksızın kullanılabilir.
Parametreler
JSON nesnesi çözülüyor.
Dönüşler
Şifrelenmiş JSON nesnesi bir Luau tablosu olarak.
Kod Örnekleri
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
Bu yöntem, bir Luau tablosunu aşağıdaki yönergelere dayanarak JSON nesnesine veya dizesine dönüştürür:
Tablonun anahtarları ya dize ya da sayı olmalıdır. Eğer bir tablo her ikisini de içeriyorsa, bir dizi öncelik kazanır (ip dize anahtarları göz ardı edilir).
Boş bir Luau tablosu ( {} ) boş bir JSON dizesi oluşturur.
Değer nil asla üretilmez.
Döngüsel masa referansları bir hata oluşturur.
Bu yöntem, geçersiz JSON olan değerleri inf ve nan gibi değerleri izin verir.Çıktılan JSON'u başka bir yerde kullanmak istiyorsanız bu sorunlara neden olabilir.
Kodlama sürecini tersine çevirmek ve bir JSON nesnesini çözümlemek için HttpService:JSONDecode() yöntemini kullanın.
Bu yöntem, HTTP isteklerinin etkinleştirilip etkinleştirilmediğine bakılmaksızın kullanılabilir.
Parametreler
Giriş Luau tablosu.
Dönüşler
Döndürülen JSON dizi.
Kod Örnekleri
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
Bu yöntem yüzde-kodları belli bir dizeyi özel karakterlerin doğru şekilde kodlanması için % ve iki onaltı karakterle kodlar ve özel karakterlerin kodlanması için rezerve edilir.
Bu, HttpService:GetAsync() / HttpService:PostAsync() veya POST medya türünün verilerinin kullanımı için URL'leri biçimlendirmek için yararlıdır, veya application/x-www-form-urlencoded ( Enum.HttpContentType.ApplicationUrlEncoded ).
durum, URL'yi şifrelediğinizde, bu yöntem geri döner.
Parametreler
Kodlanacak dize (URL).
Dönüşler
Kodlanmış dizi.
Kod Örnekleri
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
Bu yöntem bir HTTP talepgönderir.Tek bir sözlük yerine HTTP istek parametlerini yöntem parametleri olarak kabul eder ve sadece HTTP yanıtının gövdesini döndürür, hariç olmak üzere aynı şekilde çalışır RequestAsync() .Genel olarak, bu yöntem yalnızca kısaltma olarak yararlıdır ve çoğu durumda RequestAsync() kullanılmalıdır.
When true , nocache parametresi bu yöntemin aynı url ile önceki çağrılardan sonuçları kaydetmesini engeller.
Parametreler
Veri isteğinde bulunduğunuz web adresi.
İsteklerin (önbelleklerin) yanıtı saklayıp saklamadığı.
Bazı HTTP istek başlıklarını belirtmek için kullanılır.
Dönüşler
GET talepyanıt vücut.
Kod Örnekleri
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
Bu yöntem bir HTTP talepgönderir.Tek bir sözlük yerine HTTP istek parametlerini yöntem parametleri olarak kabul eder ve sadece HTTP yanıtının gövdesini döndürür, hariç olmak üzere aynı şekilde çalışır RequestAsync() .Genel olarak, bu yöntem yalnızca kısaltma olarak yararlıdır ve çoğu durumda RequestAsync() kullanılmalıdır.
When true , the compress parameter whether large request bodies will be compressed using gzip olup olmadığını kontrol eder.
Parametreler
Veriler için hedef adresi.
Gönderilen hüküm
talepile gönderilen Content-Type başlığındaki değeri değiştirir.
Verilerin gönderilirken sıkıştırılıp sıkıştırılmadığını belirler ( sıkıştırılmış )hüküm
Bazı HTTP istek başlıklarını belirtmek için kullanılır.
Dönüşler
İstek sonuçgösteren HTTP yanıtı geri gönderildi.
Kod Örnekleri
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
Bu yöntem, hedef URL, yöntem, başlıklar ve istek gövdesi verilerini belirtmek için bir sözlük kullanarak bir HTTP isteği gönderir.Alınan yanıt verilerini tanımlayan bir sözlük döndürür.Opsiyonel olarak, istek Enum.HttpCompression kullanılarak sıkıştırılabilir.
Sözlük alanları iste
<th>Tür</th><th>Gerekli</th><th>Açıklama</th></tr></thead><tbody><tr><td><code>Uzak URL</code></td><td>Sipariş</td><td>yestürkçe:yes</td><td>Bu talepiçin hedef URL. <code>http</code> veya <code>https</code> protokollerini kullanmalısınız.</td></tr><tr><td><code>Metodu</code></td><td>Sipariş</td><td>no</td><td>Bu taleptarafından kullanılan HTTP yöntemi, çoğunlukla <code>GET</code> veya <code>POST</code> .</td></tr><tr><td><code>Başlıklar</code></td><td>Sözlük</td><td>no</td><td>Bu talepile kullanılacak başlıklar sözlüğü. Çoğu HTTP başlığı burada kabul edilir, ancak tümüdeğil.</td></tr><tr><td><code>Vücut</code></td><td>Sipariş</td><td>no</td><td>İstek vücut.Kodlanmış veriler de dahil olmak üzere herhangi bir dize olabilir. Can be any dizi, including binary data.GET veya HEAD HTTP yöntemlerini kullanırken dışlanmalıdır.JSON veya diğer formatlar gönderirken <code>İçerik Türü</code> başlığını belirtmek gerekebilir.</td></tr><tr><td><code>Sıkıştır</code></td><td><code>Enum.HttpCompression'ınız</code></td><td>no</td><td>İstekteki verileri sıkıştıran opcional bir talepalanı.Değer ya <code>Enum.HttpCompression.None</code> ya da <code>Enum.HttpCompression.Gzip</code> olabilir.</td></tr></tbody>
Adı |
---|
Desteklenen HTTP yöntemleri
HTTP istek yöntemleri, yapılan isteğin amacını ve başarılı olması durumunda beklenen şeyi belirtir.Örneğin, GET istek yöntemi, talep edilen adreste bir kaynağın talep edildiğini ve başarılı olursa bu adresteki kaynakın geri döndürüleceğini sunucuya bildirir.Benzer şekilde, HEAD istek yöntemi, sunucunun bir Body elemanı olmadan bir yanıt döndürmesini bildiği dışında aynı şeyi yapar.
<th>Açıklama</th><th>Güvenli</th></tr></thead><tbody><tr><td><code>ALMAK</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/GET">ⓘ</a></td><td>GET yöntemi, belirtilen adreste kaynağı ister. Vücut parametresinin kullanımını desteklemez.</td><td>YesTürkçe:Yes</td></tr><tr><td><code>BAŞI</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/HEAD">ⓘ</a></td><td><code>BAŞ</code> yöntemi bir <code>GET</code> isteğine benzer bir yanıt talep eder, ancak yanıt vücutolmadan.<code>Vücut</code> parametresinin kullanımını desteklemez.</td><td>YesTürkçe:Yes</td></tr><tr><td><code>POST</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/POST">ⓘ</a></td><td><code>POST</code> yöntemi, verilen <code>Vücut</code> verilerini talep edilen adrese gönderir.</td><td>No</td></tr><tr><td><code>KOYUN</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PUT">ⓘ</a></td><td>The <code>PUT</code> yöntemi, tedarik edilen <code>Vücut</code> verileri içinde belirtilen kaynağın tüm mevcut döngülerini değiştirir.</td><td>No</td></tr><tr><td><code>SİLMEK</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/DELETE">ⓘ</a></td><td>The <code>SİLME</code> yöntemi, verilen <code>Vücut</code> veri adresinde belirtilen kaynağı siler.</td><td>No</td></tr><tr><td><code>SEÇENEKLER</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/OPTIONS">ⓘ</a></td><td><code>SEÇENEKLER</code> yöntemi, verilen adres için izin verilen iletişim seçeneklerini ister.</td><td>YesTürkçe:Yes</td></tr><tr><td><code>İZLEME</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/TRACE">ⓘ</a></td><td><code>İZLEME</code> yöntemi, kaynak belirtilen <code>Vücut</code> verilerinde belirtilen yola boyunca bir mesaj geri dönüş testi gerçekleştirir.</td><td>YesTürkçe:Yes</td></tr><tr><td><code>YAMA</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PATCH">ⓘ</a></td><td>The <code>YAMALI</code> yöntemi, talep edilen adreste belirtilen kaynağa kısmi değişiklikler uygular. kullanılan <code>Vücut</code> veri.</td><td>No</td></tr></tbody>
Metodu |
---|
HTTP başlıkları
Talep sözlüğünde, istekte kullanılacak özel HTTP başlıklarını belirleyebilirsiniz.Ancak, bazı başlıklar belirlenemez.Örneğin, Content-Length istek vücutbelirlenir.User-Agent ve Roblox-Id Roblox tarafından kilitlenir.Accept veya Cache-Control gibi diğer başlıklar varsayılan değerleri kullanır, ancak geçersiz kılınabilir.Daha yaygın olarak, bazı REST API'ler istek başlıklarına API anahtarlarının veya diğer hizmet doğrulamasının belirtilmesi gerekebilir.
The RequestAsync() yöntemi vücut içeriğinin formatını algılamaz.Birçok web sunucusu, belirli biçimler gönderirken Content-Type başlığının uygun şekilde ayarlanmasını gerektirir.Diğer yöntemler HttpService kullanır Enum.HttpContentType enum; bu yöntem için, ilgili enum değerleri için uygun şekilde Content-Type başlığı ayarlanır: text/plain , text/xml , application/xml , application/json veya application/x-www-form-urlencoded , ilgili enum değerlerinin yerine Content-Type başlık değerleri yerine geçer.
Cevap sözlüğü alanları
RequestAsync() aşağıdaki alanları içeren bir sözlük döndürür:
<th>Tür</th><th>Açıklama</th></tr></thead><tbody><tr><td><code>Başarı</code></td><td>Boolean Booleksiyon</td><td>talepbaşarı durumu. Bu durum sadece Durum Kodu 200 - 299 aralığında yer alıyorsa doğrudur.</td></tr><tr><td><code>Durum Kodu</code></td><td>Sayısal</td><td>Yanıtın durumunu tanımlayan HTTP yanıt kodu.</td></tr><tr><td><code>Durum Mesajı</code></td><td>Sipariş</td><td>Geri gönderilen durum geri.</td></tr><tr><td><code>Başlıklar</code></td><td>Sözlük</td><td>Bu yanıta ayarlanan başlıkların sözlüğü.</td></tr><tr><td><code>Vücut</code></td><td /><td>Yanıtın alındığı istek gövdesi (içerik).</td></tr></tbody>
Adı |
---|
Hata durumları
RequestAsync() yanıt süreleri dolduğunda veya hedef sunucu talepreddettiğinde bir hata oluşturur.Bir web hizmeti bir nedenden dolayı düşerse, bu yöntemi kullanan kodların tümüyle işlevsiz hale gelmesine neden olabilir.Bu yönteme çağrılar sarılmak genellikle iyi bir fikirdir pcall() ve gerekli bilgi mevcut değilse başarısızlık durumlarını zarif bir şekilde ele alın.
Sınırlar
Gönderilen ve alınan HTTP istekleri için mevcut sınır dakika başına 500 istek.Bu eşiğin üzerindeki istekler başarısız olur.Ayrıca, Roblox alanları dışlanır.Bu, HTTP isteklerinin www.roblox.com gibi Roblox'a ait herhangi bir siteye gönderilemeyeceği anlamına gelir.
Parametreler
Belirtilen sunucudan talep edilecek bilgileri içeren bir sözlük.
Dönüşler
Belirtilen sunucudan yanıt bilgileri içeren bir sözlük.
Kod Örnekleri
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