HttpService

Artık kullanılmayanları göster

*Bu içerik, yapay zekâ (beta) kullanılarak çevrildi ve hatalar içerebilir. Sayfayı İngilizce görüntülemek için buraya tıkla.

Oluşturulamaz
Hizmet

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.Ayrıca, birkaç Roblox web API'si de HttpService aracılığıyla erişilebilir (aşağıya bakın).

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.

Roblox alanlarını çağırmak

HttpService şu anda yalnızca Açık Bulut uç noktalarının bir kısmını çağırabilir.Bu seti zamanla genişletmeyi planlıyoruz, bu yüzden görmek istediğiniz belirli son noktalar varsa Geri bildirim düğmesini kullanın lütfen:

Gruplar
Veri Depoları

HttpService 'nin mevcut kısıtlamaları nedeniyle, Roblox alanlarına URL yol parametlerinde sadece alfanumerik karakterler ve - karakterine izin verilir.Bu, diğer özel karakterlerle veri depoları/girişlerinin şu anda HttpService 'dan erişilemez olduğu anlamına gelir.

Envanter Öğeleri
Yaratıcı Dükkanı

Bu son noktaları HttpService aracılığıyla herhangi bir diğer uç noktaya çağırdığınız aynı şekilde çağırabilirsiniz.Tek fark, isteğe bir Açık Bulut API anahtarı eklemelisiniz:

  1. İstek gönderin (aşağıdaki kod örneği).

Sınırlar şunları içerir:

  • Sadece x-api-key ve content-type başlıklarına izin verilir.
  • x-api-key başlığı bir Secret olmalıdır.
  • Sadece alfanumerik karakterler ve - karakteri URL yol parametlerinde izinlidir.
  • Sadece https:// protokolü desteklenir.
Oran Sınırlaması

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.pcall() ınız da "Taleplerin sınırı aşıldı" mesajıyla başarısız olabilir.

  • Bulut isteklerinin açılması, diğer tüm isteklerde uygulanan aynı genel sınır olan 500 HTTP isteği başına dakika başına tüketir.

  • Her Açık Bulut uç noktasının API anahtar sahibine özel sınırı vardır (çağrılar nereden gelirse gelilsin kullanıcı veya bir grup olabilir) (HttpService , web vb.).Aşağıdaki başlıklar her yanıt ile birlikte döndürülür ve sınırları ve kalan kotanızı görüntülemenize izin verir:

    • x-ratelimit-limit - API anahtar sahibine yapılabilecek toplam istek sayısı (genellikle dakika başına).
    • x-ratelimit-remaining - API anahtarının kullandığı istek sayısı hala yapılmasına izin verilir.Bu sayı 0 ise ve HTTP 429 yanıt durum kodu alırsanız, bu noktadaki oran sınırına ulaştınız.
    • x-ratelimit-reset - Oran sınırı sıfırlanmadan önce kalan saniye sayısı (yani x-ratelimit-remaining sıfırlanmadan önce x-ratelimit-limit ).
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.
  • 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

Bu kod örneği, NASA'dan veri sağlayan Açık Bildirim bir web hizmetine bir istek göndermek için HttpService'in GetAsync'ini kullanır.İstek, şu anda uzayda kaç astronot olduğu hakkında bilgi veren bir uç noktaya yapılır.Yanıt JSON formatında sağlanır, bu nedenle JSONDecode kullanılarak parçalanır.Son olarak, yanıt verileri daha sonra işlenir ve çıkıya basılır.

Kaynak kodunu bir Script'e yapıştırarak bu senaryoyu test edin (HttpService, YerelScriptlar tarafından kullanılamaz).Ayrıca, Oyun Ayarlarınızda (Ana > Oyun Ayarları) HTTP İsteklerini etkinleştirdiğinizden emin olun.

Uzaydaki Astronotlar

local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Uç noktamızın URL'sine istek gönderin
local response = HttpService:GetAsync(URL_ASTROS)
-- JSON yanıtını parçalayın
local data = HttpService:JSONDecode(response)
-- Veri tablosundaki bilgiler yanıt JSON'a bağlıdır
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

Özet

Özellikler

  • Yerel Kullanıcı Güvenliği
    Paralel oku

    HTTP isteklerinin dış web sitelerine gönderilebileceğini belirtir.

Yöntemler

Özellikler

HttpEnabled

Yerel Kullanıcı Güvenliği
Paralel oku

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

Paralel yaz

Bu yöntem bir rastgele evrensel benzersiz tanımlayıcı üretir (UUID) dize.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 ({}). Örneğin:

  • true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
  • false : db454790-7563-44ed-ab4b-397ff5df737b

Parametreler

wrapInCurlyBraces: boolean

Döndürülen dize kıvrık parantezlerde sarılmalı mı ( {} ).

Varsayılan değer: true

Dönüşler

Rastgele oluşturulan UUID.

Kod Örnekleri

This example uses HttpService's GenerateGUID method to generate and print a universally unique identifier.

HttpService GenerateGUID

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

GetSecret

Paralel yaz

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 isteğinin bir parçası olarak gönderilmesi beklenir.

Daha fazla bilgi için, kullanım kılavuzuna bakın.

Parametreler

key: string
Varsayılan değer: ""

Dönüşler

JSONDecode

Variant
Paralel yaz

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

input: string

JSON nesnesi çözülüyor.

Varsayılan değer: ""

Dönüşler

Variant

Ş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).

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

Paralel yaz

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

input: Variant

Giriş Luau tablosu.

Varsayılan değer: ""

Dönüşler

Döndürülen JSON dizesi.

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.

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

Paralel yaz

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

Örneğin, URL'yi şifrelediğinizde, bu yöntem geri döner.

Parametreler

input: string

Kodlanacak dize (URL).

Varsayılan değer: ""

Dönüşler

Kodlanmış dize.

Kod Örnekleri

Bu kod örneği, bir dizeyi bir URL'de bir argüman olarak kullanılabilecek güvenli yüzde kodlanmış bir dizeye dönüştürmek için kullanır.Sadece rezerve edilmemiş karakterlerin (harfler, sayılar ve -_.~ ) yüzde kodlanmış eşdeğerlere dönüştürülmediğini fark edin.Aksanlı karakterler de dönüştürülür (örneğin é dönüştürülür %C3 ).

HttpService UrlEncode'u

local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- Fransızca "Sinemaya gittim" için
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).

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

Bekletir

Bu yöntem bir HTTP GET.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

url: Variant

Veri isteğinde bulunduğunuz web adresi.

Varsayılan değer: ""
nocache: boolean

İsteklerin (önbelleklerin) yanıtı saklayıp saklamadığı.

Varsayılan değer: false
headers: Variant

Bazı HTTP istek başlıklarını belirtmek için kullanılır.

Varsayılan değer: ""

Dönüşler

GET isteğinin yanıt gövdesi.

Kod Örnekleri

Bu kod örneği, NASA'dan veri sağlayan Açık Bildirim bir web hizmetine bir istek göndermek için HttpService'in GetAsync'ini kullanır.İstek, şu anda uzayda kaç astronot olduğu hakkında bilgi veren bir uç noktaya yapılır.Yanıt JSON formatında sağlanır, bu nedenle JSONDecode kullanılarak parçalanır.Son olarak, yanıt verileri daha sonra işlenir ve çıkıya basılır.

Kaynak kodunu bir Script'e yapıştırarak bu senaryoyu test edin (HttpService, YerelScriptlar tarafından kullanılamaz).Ayrıca, Oyun Ayarlarınızda (Ana > Oyun Ayarları) HTTP İsteklerini etkinleştirdiğinizden emin olun.

Uzaydaki Astronotlar

local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Uç noktamızın URL'sine istek gönderin
local response = HttpService:GetAsync(URL_ASTROS)
-- JSON yanıtını parçalayın
local data = HttpService:JSONDecode(response)
-- Veri tablosundaki bilgiler yanıt JSON'a bağlıdır
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

PostAsync

Bekletir

Bu yöntem bir HTTP POST.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

url: Variant

Veriler için hedef adresi.

Varsayılan değer: ""
data: string

Gönderilen veriler.

Varsayılan değer: ""
content_type: Enum.HttpContentType

İstek ile gönderilen Content-Type başlığındaki değeri değiştirir.

Varsayılan değer: "ApplicationJson"
compress: boolean

Verilerin gönderilirken sıkıştırılıp sıkıştırılmadığını belirler ( sıkıştırılmış ).

Varsayılan değer: false
headers: Variant

Bazı HTTP istek başlıklarını belirtmek için kullanılır.

Varsayılan değer: ""

Dönüşler

İstek sonucunu 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).

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

Bekletir

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>yes
türkçe:yes</td>
<td>Bu istek iç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 istek tarafı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 istek ile kullanılacak başlıklar sözlüğü. Çoğu HTTP başlığı burada kabul edilir, ancak hepsi değil.</td>
</tr>
<tr>
<td><code>Vücut</code></td>
<td>Sipariş</td>
<td>no</td>
<td>İstek gövdesi.Kodlanmış veriler de dahil olmak üzere herhangi bir dize olabilir. Can be any string, 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 sıkıştırma alanı.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>Yes
Tü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 bedeni olmadan.<code>Vücut</code> parametresinin kullanımını desteklemez.</td>
<td>Yes
Tü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>Yes
Tü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>Yes
Tü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 gövdesinden belirlenir.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>İstekin baş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 mesajı.</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 isteği reddettiğ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.

Parametreler

requestOptions: Dictionary

Belirtilen sunucudan talep edilecek bilgileri içeren bir sözlük.

Varsayılan değer: ""

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.

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

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

Etkinlikler