HttpService

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile
Assistenza

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.Inoltre, alcune API web di Roblox possono anche essere accessibili tramite HttpService (vedi sotto).

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

Chiamare i domini di Roblox

HttpService attualmente può chiamare solo un sottinsieme degli endpoint Open Cloud.Pianifichiamo di estendere questo set nel tempo quindi per favore usa il pulsante Feedback se hai punti finali specifici che vorresti vedere:

Gruppi
Magazzini di dati

A causa delle attuali restrizioni su HttpService , sono consentiti solo caratteri alfanumerici e il carattere - nel parametro percorso URL ai domini Roblox.Questo significa che i Data Store/azioni con altri caratteri speciali non sono attualmente accessibili da HttpService .

Oggetti inventario
Negozio creatori

Puoi chiamare questi endpoint allo stesso modo in cui chiameresti qualsiasi altro endpoint tramite HttpService .La sola differenza è che devi includere una chiave Open Cloud API nella richiesta:

  1. Fai la richiesta (esempio di codice qui sotto).

Le limitazioni includono quanto segue:

  • Sono consentiti solo i x-api-key e content-type headers.
  • L'intestazione x-api-key deve essere un Secret.
  • Solo caratteri alfanumerici e il carattere - sono consentiti nei parametri del percorso URL.
  • Solo il protocollo https:// è supportato.
Limitazione della tariffa

Per ciascun server di gioco Roblox, c'è un limite di 500 richieste HTTP al minuto.Superare questo può causare l'interruzione dei metodi di invio delle richieste per circa 30 secondi.Il tuo pcall() può anche fallire con un messaggio di "Limite del numero di richieste superato."

  • Le richieste Open Cloud aperte consumano lo stesso limite generale di 500 richieste HTTP al minuto applicato a tutte le altre richieste.

  • Ogni endpoint Open Cloud ha il proprio limite per ogni proprietario di chiave API (può essere un utente o un gruppo) che viene applicato indipendentemente da dove provengono le chiamate ( HttpService , il web, ecc.).I seguenti intestazioni vengono restituiti con ogni risposta e ti consentono di visualizzare i limiti e la tua quota rimanente:

    • x-ratelimit-limit - Il numero totale di richieste consentite per ogni proprietario di chiave API (solitamente per minuto).
    • x-ratelimit-remaining - Il numero di richieste che la chiave API utilizzata può ancora fare è ancora consentito.Se questo numero è 0 e ricevi un codice stato HTTP 429 di risposta, allora hai raggiunto il limite di velocità per questo endpoint.
    • x-ratelimit-reset - Il numero di secondi rimanenti prima che il limite di tasso venga ripristinato (cioè prima che x-ratelimit-remaining venga ripristinato a x-ratelimit-limit ).
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.
  • 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

Questo esempio di codice utilizza HttpService's GetAsync per inviare una richiesta a Open Notify, un servizio web che fornisce dati dalla NASA.La richiesta viene fatta a un endpoint che fornisce informazioni su quanti astronauti sono attualmente nello spazio.La risposta è fornita nel formato JSON, quindi viene analizzata utilizzando JSONDecode.Infine, i dati di risposta vengono quindi elaborati e stampati sull'Output.

Prova questo script incollando il codice sorgente in uno script (HttpService non può essere utilizzato da LocalScripts).Inoltre, assicurati di abilitare le richieste HTTP nelle tue impostazioni di gioco (Home > Impostazioni di gioco).

Astronauti nello Spazio

local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Fai la richiesta al nostro URL endpoint
local response = HttpService:GetAsync(URL_ASTROS)
-- Analizza la risposta JSON
local data = HttpService:JSONDecode(response)
-- Le informazioni nella tabella dei dati dipendono dalla risposta JSON
if data.message == "success" then
print("There are currently " .. data.number .. " astronauts in space:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " is on " .. person.craft)
end
end

This code sample uses HttpService's GetAsync to make a request to an endpoint at Open Notify, a website that provides information from NASA. The endpoint provides information on the current location of the International Space Station. This example uses a defensive coding technique that you should use when making web requests. It wraps the call to GetAsync and JSONDecode in pcall, which protects our script from raising an error if either of these fail. Then, it checks the raw response for all proper data before using it. All of this is put inside a function that returns true or false depending of the request's success.

Whenever you're working with web requests, you should prepare for anything to go wrong. Perhaps your web endpoint changes or goes down - you don't want your game scripts raising errors and breaking your game. You want to handle both success and failure gracefully - have a plan in case your data is not available. Use pcall and make plenty of validity checks (if statements) on your data to make sure you're getting exactly what you expect.

Where is the International Space Station?

local HttpService = game:GetService("HttpService")
-- Where is the International Space Station right now?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- Use pcall in case something goes wrong
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- Did our request fail or our JSON fail to parse?
if not data then
return false
end
-- Fully check our data for validity. This is dependent on what endpoint you're
-- to which you're sending your requests. For this example, this endpoint is
-- described here: http://open-notify.org/Open-Notify-API/ISS-Location-Now/
if data.message == "success" and data.iss_position then
if data.iss_position.latitude and data.iss_position.longitude then
print("The International Space Station is currently at:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("Success")
else
print("Something went wrong")
end

Pastebin.com is a website that allows users to paste text (usually source code) for others to view publicly. This code sample uses HttpService PostAsync and the pastebin web API to automatically create a new public paste on the website. Since pastebin's API is designed to take data in as a URL encoded string, the code uses a for-loop to turn the dataFields table into a URL encoded string, such as hello=world&foo=bar. This is used as the HTTP POST data.

Test this code by first going to pastebin.com/api#1 and getting an API key (you'll need a pastebin account to do this). Then, paste your unique developer API key into the field api_dev_key in the code sample's dataFields table. Fill in any other information about the post you want to make, then run this code in a Script (not a LocalScript). If all goes well, you'll get a URL to your new paste in the Output window (or some error string from pastebin).

New Pastebin Post

local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API developer key from
-- https://pastebin.com/api#1
["api_dev_key"] = "FILL THIS WITH YOUR API DEVELOPER KEY",
["api_option"] = "paste", -- keep as "paste"
["api_paste_name"] = "HttpService:PostAsync", -- paste name
["api_paste_code"] = "Hello, world", -- paste content
["api_paste_format"] = "text", -- paste format
["api_paste_expire_date"] = "10M", -- expire date
["api_paste_private"] = "0", -- 0=public, 1=unlisted, 2=private
["api_user_key"] = "", -- user key, if blank post as guest
}
-- The pastebin API uses a URL encoded string for post data
-- Other APIs might use JSON, XML or some other format
local data = ""
for k, v in pairs(dataFields) do
data = data .. ("&%s=%s"):format(HttpService:UrlEncode(k), HttpService:UrlEncode(v))
end
data = data:sub(2) -- Remove the first &
-- Here's the data we're sending
print(data)
-- Make the request
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- The response will be the URL to the new paste (or an error string if something was wrong)
print(response)

This code sample demonstrates sending a single HTTP PATCH request with JSON data to the Open Cloud Update Group Membership endpoint. Every Open Cloud endpoint requires adding your API key to the "x-api-key" header to receive a successful response. The generated API key must be stored as a Secret that can later be retrieved with HttpService:GetSecret("API KEY SECRET NAME").

Open Cloud via HttpService

-- Remember to set enable HTTP Requests in game settings!
local HttpService = game:GetService("HttpService")
local groupId = "your_group_id"
local membershipId = "your_membership_id"
local roleId = "your_role_id"
local function request()
local response = HttpService:RequestAsync({
Url = `https://apis.roblox.com/cloud/v2/groups/{groupId}/memberships/{membershipId}`, -- Updates a user's group membership
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- When sending JSON, set this!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Set in Creator Hub
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("The response was successful:", response.StatusCode, response.StatusMessage)
else
print("The response returned an error:", response.StatusCode, response.StatusMessage)
end
print("Response body:\n", response.Body)
print("Response headers:\n", HttpService:JSONEncode(response.Headers))
end
-- Remember to wrap the function in a 'pcall' to prevent the script from breaking if the request fails
local success, message = pcall(request)
if not success then
print("The Http request failed to send:", message)
end

Sommario

Proprietà

  • Sicurezza Utente Locale
    Lettura Parallela

    Indica se le richieste HTTP possono essere inviate a siti web esterni.

Metodi

Proprietà

HttpEnabled

Sicurezza Utente Locale
Lettura Parallela

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

Scrivi Parallelo

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

wrapInCurlyBraces: boolean

Se la stringa restituita debba essere avvolta in parentesi graffe ( {} ).

Valore predefinito: true

Restituzioni

L'UUID generato casualmente.

Campioni di codice

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

Scrivi Parallelo

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 richiesta HTTP.

Per maggiori informazioni, vedi la guida d'uso.

Parametri

key: string
Valore predefinito: ""

Restituzioni

JSONDecode

Variant
Scrivi Parallelo

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

input: string

L'oggetto JSON decodificato.

Valore predefinito: ""

Restituzioni

Variant

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

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

Scrivi Parallelo

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 array JSON 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

input: Variant

La tabella di input Luau.

Valore predefinito: ""

Restituzioni

La stringa JSON 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.

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

Scrivi Parallelo

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

input: string

La stringa (URL) da decodificare.

Valore predefinito: ""

Restituzioni

La stringa codificata.

Campioni di codice

Questo esempio di codice utilizza UrlEncode per convertire una stringa in una stringa sicura, percent-encoded che può essere utilizzata in un URL come argomento.Nota come solo i caratteri non riservati (lettere, numeri e -_.~ ) non vengono trasformati in equivalenti percentuali codificati.Anche i personaggi con accenti vengono trasformati (ad esempio é viene trasformato in %C3).

HttpService UrlEncode

local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- Francese per "Sono andato al cinema"
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

Resa

Questo metodo invia una richiesta HTTP 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

url: Variant

L'indirizzo web da cui stai richiedendo dati.

Valore predefinito: ""
nocache: boolean

Se la richiesta memorizza (cached) la risposta.

Valore predefinito: false
headers: Variant

Utilizzato per specificare alcuni headers di richiesta HTTP.

Valore predefinito: ""

Restituzioni

Il corpo della risposta della richiesta GET.

Campioni di codice

Questo esempio di codice utilizza HttpService's GetAsync per inviare una richiesta a Open Notify, un servizio web che fornisce dati dalla NASA.La richiesta viene fatta a un endpoint che fornisce informazioni su quanti astronauti sono attualmente nello spazio.La risposta è fornita nel formato JSON, quindi viene analizzata utilizzando JSONDecode.Infine, i dati di risposta vengono quindi elaborati e stampati sull'Output.

Prova questo script incollando il codice sorgente in uno script (HttpService non può essere utilizzato da LocalScripts).Inoltre, assicurati di abilitare le richieste HTTP nelle tue impostazioni di gioco (Home > Impostazioni di gioco).

Astronauti nello Spazio

local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- Fai la richiesta al nostro URL endpoint
local response = HttpService:GetAsync(URL_ASTROS)
-- Analizza la risposta JSON
local data = HttpService:JSONDecode(response)
-- Le informazioni nella tabella dei dati dipendono dalla risposta JSON
if data.message == "success" then
print("There are currently " .. data.number .. " astronauts in space:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. " is on " .. person.craft)
end
end

This code sample uses HttpService's GetAsync to make a request to an endpoint at Open Notify, a website that provides information from NASA. The endpoint provides information on the current location of the International Space Station. This example uses a defensive coding technique that you should use when making web requests. It wraps the call to GetAsync and JSONDecode in pcall, which protects our script from raising an error if either of these fail. Then, it checks the raw response for all proper data before using it. All of this is put inside a function that returns true or false depending of the request's success.

Whenever you're working with web requests, you should prepare for anything to go wrong. Perhaps your web endpoint changes or goes down - you don't want your game scripts raising errors and breaking your game. You want to handle both success and failure gracefully - have a plan in case your data is not available. Use pcall and make plenty of validity checks (if statements) on your data to make sure you're getting exactly what you expect.

Where is the International Space Station?

local HttpService = game:GetService("HttpService")
-- Where is the International Space Station right now?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- Use pcall in case something goes wrong
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- Did our request fail or our JSON fail to parse?
if not data then
return false
end
-- Fully check our data for validity. This is dependent on what endpoint you're
-- to which you're sending your requests. For this example, this endpoint is
-- described here: http://open-notify.org/Open-Notify-API/ISS-Location-Now/
if data.message == "success" and data.iss_position then
if data.iss_position.latitude and data.iss_position.longitude then
print("The International Space Station is currently at:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("Success")
else
print("Something went wrong")
end

PostAsync

Resa

Questo metodo invia una richiesta HTTP 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

url: Variant

L'indirizzo di destinazione per i dati.

Valore predefinito: ""
data: string

I dati in arrivo.

Valore predefinito: ""
content_type: Enum.HttpContentType

Modifica il valore nell'intestazione Content-Type inviata con la richiesta.

Valore predefinito: "ApplicationJson"
compress: boolean

Determina se i dati sono compressi ( zippati ) quando inviati.

Valore predefinito: false
headers: Variant

Utilizzato per specificare alcuni headers di richiesta HTTP.

Valore predefinito: ""

Restituzioni

La risposta HTTP inviata indietro che indica il risultato della 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).

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

Resa

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.</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 restituito.</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.

Parametri

requestOptions: Dictionary

Un dizionario che contiene le informazioni da richiedere al server specificato.

Valore predefinito: ""

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.

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

Eventi