HttpService
*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.
HttpService consente alle richieste HTTP di essere inviate dai server di gioco utilizzando RequestAsync, GetAsync e PostAsync .Questo servizio consente ai giochi di essere integrati con servizi web off-Roblox come analitica, archiviazione dati, configurazione del server remoto, segnalazione degli errori, calcoli avanzati o comunicazione in tempo reale.
HttpService ospita anche i metodi JSONEncode e JSONDecode che sono utili per comunicare con servizi che utilizzano il formato JSON.Inoltre, il metodo GenerateGUID fornisce etichette casuali da 128 bit che possono essere trattate come probabilisticamente uniche in una varietà di scenari.
Dovresti inviare solo richieste HTTP a piattaforme terze di fiducia per evitare di rendere la tua esperienza vulnerabile ai rischi di sicurezza.
Questa proprietà non può essere interagita durante l'Tempo esecuzione.
Abilita richieste HTTP
I metodi di invio delle richieste non sono abilitati per impostazione predefinita. Per inviare richieste, devi abilitare le richieste HTTP per la tua esperienza.
Uso nei plugin
HttpService può essere utilizzato dai plugin di Studio.Potrebbero farlo per controllare gli aggiornamenti, inviare dati di utilizzo, scaricare contenuti o altre logiche aziendali.La prima volta che un plugin tenta di farlo, l'utente può essere richiesto di dare al plugin l'autorizzazione a comunicare con il particolare indirizzo web.Un utente può accettare, negare e revocare tali autorizzazioni in qualsiasi momento attraverso la finestra Gestione plugin .
I plugin possono anche comunicare con altri software in esecuzione sullo stesso computer attraverso i host localhost e 127.0.0.1.Eseguendo programmi compatibili con tali plugin, puoi estendere la funzionalità del tuo plugin al di là delle normali capacità di Studio, come interagire con il sistema file del tuo computer.Attenzione che tale software deve essere distribuito separatamente dal plugin stesso e può rappresentare un pericolo per la sicurezza se non sei attento.
Considerazioni supplementari
- Ci sono restrizioni portuali.Non puoi utilizzare il porto 1194 o qualsiasi porto inferiore a 1024, tranne 80 e 443.Se tenti di utilizzare un porto bloccato, riceverai un errore 403 Forbidden o ERR_ACCESS_DENIED.
- Per ciascun Serverdi gioco Roblox, c'è un limite di 500 richieste HTTP al minuto.Superare questo può causare l'interruzione completa dei metodi di invio delle richieste per circa 30 secondi.
- Le richieste non possono essere inviate a nessun sito Web di Roblox, come www.roblox.com.
- Le richieste Web possono fallire per molti motivi, quindi è importante "codificare in modo difensivo" (utilizzare pcall() ) e avere un piano per quando le richieste falliscono.
- Sebbene il protocollo http:// sia supportato, dovresti usare https:// ovunque sia possibile.
- Le richieste inviate dovrebbero fornire una forma sicura di autenticazione, come una chiave segreta precondivisa, in modo che gli attori cattivi non possano fingere di essere uno dei tuoi server di gioco Roblox.
- Si tenga presente la capacità generale e le politiche di limitazione delle richieste dei server web a cui vengono inviate le richieste.
Campioni di codice
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)
Sommario
Proprietà
Indica se le richieste HTTP possono essere inviate a siti web esterni.
Metodi
Genera una Stringacasuale UUID/GUID, opzionalmente con parentesi curly.
Restituisce un Secret dal Negoziodi segreti.
Decodifica una stringa JSON in una tabella Luau.
Genera una stringa JSON da una tabella Luau.
Sostituisce i caratteri non sicuri URL con "%" e due caratteri esadecimali.
Invia una RichiestaHTTP GET .
- PostAsync(url : Variant,data : string,content_type : Enum.HttpContentType,compress : boolean,headers : Variant):string
Invia una RichiestaHTTP POST .
Invia una richiesta HTTP utilizzando qualsiasi metodo HTTP dato un dizionario di informazioni.
Proprietà
HttpEnabled
Quando è impostato su true , consente agli script di inviare richieste ai siti web utilizzando HttpService:GetAsync() , HttpService:PostAsync() e HttpService:RequestAsync() .
Questa proprietà deve essere attivata attraverso l'interfaccia Impostazioni di gioco in Studio, o per esperienze non pubblicate impostando questa proprietà su utilizzando la barra di comando :
game:GetService("HttpService").HttpEnabled = true
Metodi
GenerateGUID
Questo metodo genera una identificatore casuale universalmente unico ( UUID ) Stringa.I sedici ottetti di un UUID sono rappresentati come 32 cifre esadecimali (base 16) mostrate in cinque gruppi separati da trattini nella forma 8-4-4-4-12 per un totale di 36 caratteri, ad esempio 123e4567-e89b-12d3-a456-426655440000 .
La specifica UUID utilizzata è Versione 4 ( casuale ), variante 1 (DCE 1.1, ISO/IEC 11578:1996).Gli UUID di questa versione sono quelli più comunemente utilizzati a causa della loro semplicità, poiché vengono generati completamente casualmente.Si noti che questa versione non ha alcune caratteristiche che altre versioni UUID hanno, come timbri temporali codificati, indirizzi MAC o ordinamento basato sul tempo come UUIDv7 o ULID.
Ci sono oltre 5.3×10 36 UUID unici v4, in cui la probabilità di trovare un duplicato all'interno di 103 trilioni di UUID è una su miliardo.
L'argomento wrapInCurlyBraces determina se la stringa restituita è avvolta in parentesi graffe ( {} ). Ad esempio:
- true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
- false : db454790-7563-44ed-ab4b-397ff5df737b
Parametri
Se la stringa restituita debba essere avvolta in parentesi graffe ( {} ).
Restituzioni
L'UUID generato casualmente.
Campioni di codice
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
Questo metodo restituisce un valore precedentemente aggiunto allo store di segreti per l'esperienza.Il contenuto segreto non è stampabile e non è disponibile quando l'esperienza viene eseguita localmente.
Il restituito Secret può essere trasformato utilizzando metodi integrati come Secret:AddPrefix() . Si prevede che venga inviato come parte di una RichiestaHTTP.
Per maggiori informazioni, vedi la guida d'uso.
Parametri
Restituzioni
JSONDecode
Questo metodo trasforma un oggetto JSON o un array in una tabella Luau con le seguenti caratteristiche:
- Le chiavi della tabella sono stringhe o numeri ma non entrambi. Se un oggetto JSON contiene entrambi, le chiavi di stringa vengono ignorate.
- Un oggetto JSON vuoto genera una tabella Luau vuota ( {} ).
- Se la stringa input non è un oggetto JSON valido, questo metodo lancerà un errore.
Per codificare una tabella Luau in un oggetto JSON, usa il metodo HttpService:JSONEncode().
Questo metodo può essere utilizzato indipendentemente dal fatto che le richieste HTTP siano abilitate.
Parametri
L'oggetto JSON decodificato.
Restituzioni
L'oggetto JSON decodificato come tabella Luau.
Campioni di codice
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
Questo metodo trasforma una tabella Luau in un oggetto JSON o array in base alle seguenti linee guida:
Le chiavi della tabella devono essere stringhe o numeri. Se una tabella contiene entrambi, un array ha la priorità (le chiavi delle stringhe vengono ignorate).
Un tavolo Luau vuoto ( {} ) genera un vettoreJSON vuoto.
Il valore nil non viene mai generato.
Le referenze di tab cicliche causano un errore.
Questo metodo consente valori come inf e nan che non sono JSON validi.Questo può causare problemi se vuoi utilizzare l'output JSON altrove.
Per invertire il processo di encoding e decodificare un oggetto JSON, usa il metodo HttpService:JSONDecode().
Questo metodo può essere utilizzato indipendentemente dal fatto che le richieste HTTP siano abilitate.
Parametri
La tabella di input Luau.
Restituzioni
La StringaJSON restituita.
Campioni di codice
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
Questo metodo percentualizza una determinata stringa in modo che i caratteri riservati siano correttamente codificati con % e due caratteri esadecimali.
Questo è utile quando si formattano gli URL per l'uso con HttpService:GetAsync() / HttpService:PostAsync() , o POST i dati del tipo di media application/x-www-form-urlencoded ( Enum.HttpContentType.ApplicationUrlEncoded ).
Ad esempio, quando si codifica l'URL https://www.roblox.com/discover#/, questo metodo restituisce https%3A%2F%2Fwww%2Eroblox%2Ecom%2Fdiscover%23%2F .
Parametri
La stringa (URL) da decodificare.
Restituzioni
La Stringacodificata.
Campioni di codice
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
Questo metodo invia una RichiestaHTTP GET.Funziona in modo simile a RequestAsync() tranne che accetta i parametri della richiesta HTTP come parametri del metodo invece di un singolo dizionario e restituisce solo il corpo della risposta HTTP.Generalmente, questo metodo è utile solo come abbreviazione e RequestAsync() dovrebbe essere utilizzato nella maggior parte dei casi.
Quando true , il parametro nocache impedisce a questo metodo di memorizzare i risultati della cache delle chiamate precedenti con lo stesso url.
Parametri
L'indirizzo web da cui stai richiedendo dati.
Se la richiesta memorizza (cached) la risposta.
Utilizzato per specificare alcuni headers di richiesta HTTP.
Restituzioni
Il corpo della risposta della RichiestaGET.
Campioni di codice
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
Questo metodo invia una RichiestaHTTP POST.Funziona in modo simile a RequestAsync() tranne che accetta i parametri della richiesta HTTP come parametri del metodo invece di un singolo dizionario e restituisce solo il corpo della risposta HTTP.Generalmente, questo metodo è utile solo come abbreviazione e RequestAsync() dovrebbe essere utilizzato nella maggior parte dei casi.
Quando true , il parametro compress controlla se i grandi corpi di richiesta saranno compressi usando gzip .
Parametri
L'indirizzo di destinazione per i dati.
I dati in Sentenza
Modifica il valore nell'intestazione Content-Type inviata con la Richiesta.
Determina se i dati sono compressi ( zippati ) quando Sentenza
Utilizzato per specificare alcuni headers di richiesta HTTP.
Restituzioni
La risposta HTTP inviata indietro che indica il Risultatodella richiesta.
Campioni di codice
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
Questo metodo invia una richiesta HTTP utilizzando un dizionario per specificare i dati della richiesta, come l'URL target, il metodo, le intestazioni e i dati del corpo della richiesta.Restituisce un dizionario che descrive i dati di risposta ricevuti.Opzionalmente, la richiesta può essere compressa utilizzando Enum.HttpCompression .
Richiedi campi dizionario
<th>Tipo</th><th>Richiesto</th><th>Descrizione</th></tr></thead><tbody><tr><td><code>Url</code></td><td>Strumento</td><td>sì</td><td>L'URL target per questa Richiesta. Deve utilizzare <code>http</code> o <code>https</code> protocolli.</td></tr><tr><td><code>Metodo</code></td><td>Strumento</td><td>no</td><td>Il metodo HTTP utilizzato da questa Richiesta, più spesso <code>GET</code> o <code>POST</code>.</td></tr><tr><td><code>Titoli</code></td><td>Dizionario</td><td>no</td><td>Un dizionario di intestazioni da utilizzare con questa Richiesta. La maggior parte degli intestati HTTP sono accettati qui, ma non tutti/tutte.</td></tr><tr><td><code>Corpo</code></td><td>Strumento</td><td>no</td><td>Il corpo della richiesta.Può essere qualsiasi Stringa, inclusi dati binari.Deve essere escluso quando si utilizzano i metodi HTTP <code>GET</code> o <code>HEAD</code>.Potrebbe essere necessario specificare il <code>Header del tipo di contenuto</code> quando si invia JSON o altri formati.</td></tr><tr><td><code>Comprimere</code></td><td><code>Enumerazione.HttpCompression</code></td><td>no</td><td>Un campo di compressione opzionale che comprimerà i dati nella Richiesta.Il valore può essere <code>Enum.HttpCompression.None</code> o <code>Enum.HttpCompression.Gzip</code>.</td></tr></tbody>
Nome |
---|
Metodi HTTP supportati
I metodi di richiesta HTTP specificano lo scopo della richiesta che viene effettuata e cosa si aspetta se la richiesta ha successo.Ad esempio, il metodo di richiesta GET dice al server all'indirizzo richiesto che una risorsa viene richiesta e, se ha successo, la risorsa a quell'indirizzo verrà restituita.Allo stesso modo, il metodo di richiesta HEAD fa lo stesso tranne che il server sa restituire una risposta senza un elemento Body.
<th>Descrizione</th><th>Sicuro</th></tr></thead><tbody><tr><td><code>OTTENERE</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/GET">ⓘ</a></td><td>Il metodo <code>GET</code> richiede la risorsa all'indirizzo specificato. Non supporta l'uso del parametro <code>Corpo</code>.</td><td>Sì</td></tr><tr><td><code>TESTA</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/HEAD">ⓘ</a></td><td>Il metodo <code>HEAD</code> richiede una risposta identica a una Richiesta<code>GET</code>, ma senza corpo di risposta.Non supporta l'uso del parametro <code>Corpo</code>.</td><td>Sì</td></tr><tr><td><code>POST</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/POST">ⓘ</a></td><td>Il metodo <code>POST</code> invia i dati del <code>Corpo</code> forniti all'indirizzo richiesto.</td><td>No</td></tr><tr><td><code>PUT</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PUT">ⓘ</a></td><td>Il metodo <code>PUT</code> sostituisce tutte le iterazioni attuali della risorsa specificata all'interno dei dati forniti <code>Corpo</code>.</td><td>No</td></tr><tr><td><code>ELIMINA</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/DELETE">ⓘ</a></td><td>Il metodo <code>ELIMINA</code> elimina la risorsa specificata nei dati forniti <code>Corpo</code> nell'indirizzo richiesto.</td><td>No</td></tr><tr><td><code>OPZIONI</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/OPTIONS">ⓘ</a></td><td>Il metodo <code>OPTIONS</code> richiede le opzioni di comunicazione consentite per l'indirizzo fornito.</td><td>Sì</td></tr><tr><td><code>TRACE</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/TRACE">ⓘ</a></td><td>Il metodo <code>TRACE</code> esegue un test di loop-back del messaggio lungo il percorso per la risorsa specificata nei dati forniti <code>Corpo</code>.</td><td>Sì</td></tr><tr><td><code>PATCH</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PATCH">ⓘ</a></td><td>Il metodo <code>PATCH</code> applica modifiche parziali alla risorsa specificata nei dati <code>Corpo</code> forniti nell'indirizzo richiesto.</td><td>No</td></tr></tbody>
Metodo |
---|
Header HTTP
Nel dizionario delle richieste, puoi specificare i header HTTP personalizzati da utilizzare nella Richiesta.Tuttavia, alcuni header non possono essere specificati.Ad esempio, Content-Length è determinato dal corpo della richiesta.User-Agent e Roblox-Id sono bloccati da Roblox.Altri intestazioni come Accept o Cache-Control utilizzano i valori predefiniti ma possono essere sovrascritte.Più comunemente, alcune API REST possono richiedere che le chiavi API o un'altra autenticazione del servizio siano specificate negli header della richiesta.
Il metodo RequestAsync() non rileva il formato del contenuto del corpo.Molti server web richiedono che l'intestazione Content-Type venga impostata correttamente quando si inviano determinati formati.Altri metodi di utilizzano l'enum ; per questo metodo imposta il Header appropriatamente: , , , o sono valori di intestazione di sostituzione per i rispettivi valori di enum.
Campi del dizionario di risposta
RequestAsync() restituisce un dizionario che contiene i seguenti campi:
<th>Tipo</th><th>Descrizione</th></tr></thead><tbody><tr><td><code>Successo</code></td><td>Booleano</td><td>Lo stato di successo della Richiesta. Questo è vero se e solo se il <code>StatusCode</code> si trova nella gamma <code>200</code> - <code>299</code>.</td></tr><tr><td><code>StatisticheCode</code></td><td>Intero</td><td>Il codice HTTP di risposta che identifica lo stato della risposta.</td></tr><tr><td><code>Messaggio stato</code></td><td>Strumento</td><td>Il messaggio di stato che è stato Indietro.</td></tr><tr><td><code>Titoli</code></td><td>Dizionario</td><td>Un dizionario di intestazioni che sono state impostate in questa risposta.</td></tr><tr><td><code>Corpo</code></td><td /><td>Il corpo della richiesta (contenuto) ricevuto nella risposta.</td></tr></tbody>
Nome |
---|
Casi di errore
RequestAsync() solleva un errore se i tempi di risposta scadono o se il server target rifiuta la Richiesta.Se un servizio web cade per qualche motivo, può causare script che utilizzano questo metodo a smettere di funzionare del tutto.Spesso è una buona idea avvolgere le chiamate a questo metodo in pcall() e gestire elegantemente i casi di fallimento se le informazioni richieste non sono disponibili.
Limitazioni
La limitazione attuale per l'invio e la ricezione di richieste HTTP è di 500 richieste al minuto.Le richieste oltre questa soglia falliranno.Inoltre, sono esclusi i domini di Roblox.Questo significa che le richieste HTTP non possono essere inviate a nessun sito di proprietà di Roblox come www.roblox.com.
Parametri
Un dizionario che contiene le informazioni da richiedere al server specificato.
Restituzioni
Un dizionario che contiene le informazioni di risposta dal server specificato.
Campioni di codice
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