HttpService 는 HTTP 요청을 RequestAsync , GetAsync 및 PostAsync 을 사용하여 게임 서버에서 보낼 수 있도록 허용합니다.이 서비스를 통해 게임은 애널리틱스, 데이터 저장소, 원격 서버 구성, 오류 보고, 고급 계산 또는 실시간 통신과 같은 오프 Roblox 웹 서비스와 통합할 수 있습니다.
HttpService 또한 JSONEncode 및 JSONDecode 메서드를 포함하며, JSON 형식을 사용하는 서비스와 통신하는 데 유용합니다.또한, GenerateGUID 메서드는 다양한 시나리오에서 확률적으로 고유하게 처리할 수 있는 128비트 레이블을 제공합니다.
경험을 보안 위험에 노출시키지 않도록 신뢰할 수 있는 타사 플랫폼에 HTTP 요청만 보내야 합니다.
이 속성은 런타임에 상호 작용할 수 없습니다.
HTTP 요청 활성화
요청 전송 방법은 기본적으로 활성화되지 않습니다. 요청을 보내려면 경험에서 HTTP 요청을 활성화해야 합니다.
플러그인에서 사용
HttpService Studio 플러그인에서 사용할 수 있습니다.업데이트를 확인하거나, 사용 데이터를 전송하거나, 콘텐츠를 다운로드하거나, 다른 비즈니스 논리를 수행하기 위해 이렇게 할 수 있습니다.플러그인이 처음으로 이것을 시도할 때 사용자에게 특정 웹 주소와 통신하기 위한 플러그인 권한을 부여하라는 메시지가 표시될 수 있습니다.사용자는 언제든지 플러그인 관리 창을 통해 이러한 권한을 수락하거나 거부하고 취소할 수 있습니다.
플러그인은 또한 localhost 및 127.0.0.1 호스트를 통해 동일한 컴퓨터에서 실행 중인 다른 소프트웨어와 통신할 수 있습니다.이러한 플러그인과 호환되는 프로그램을 실행하여 플러그인의 기능을 Studio의 일반 기능 이상으로 확장할 수 있습니다. 예를 들어, 컴퓨터의 파일 시스템과 상호작용하는 것입니다.이러한 소프트웨어는 플러그인 자체와 별도로 배포되어야 하며, 주의하지 않으면 보안 위험을 초래할 수 있습니다.
추가 고려 사항
- 포트 제한이 있습니다.1194나 1024 이하의 모든 포트는 80와 443을 제외하고 사용할 수 없습니다.차단된 포트를 사용하려고 하면 403 Forbidden 또는 ERR_ACCESS_DENIED 오류가 발생합니다.
- Roblox 게임 서버마다 분당 500 HTTP 요청의 제한이 있습니다.이를 초과하면 요청 전송 방법이 약 30초 동안 완전히 중단될 수 있습니다.
- www.roblox.com과 같은 Roblox 웹사이트에 요청할 수 없습니다.
- 웹 요청은 여러 가지 이유로 실패할 수 있으므로, "방어적으로 코딩"하고(pcall() 사용) 요청이 실패할 경우 계획을 수립하는 것이 중요합니다
- 비록 http:// 프로토콜이 지원되지만, 가능하면 https:// 어디서나 사용해야 합니다.
- 전송된 요청은 사전 공유된 비밀 키와 같은 안전한 인증 방식을 제공하여 악의적인 행위자가 Roblox 게임 서버 중 하나로 가장할 수 없도록 합니다.
- 요청이 전송되는 웹 서버의 일반 용량 및 속도 제한 정책을 알아두십시오.
코드 샘플
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
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
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)
요약
속성
HTTP 요청을 외부 웹사이트에 전송할 수 있는지 여부를 나타냅니다.
메서드
옵션으로 굵은 괄호를 사용하여 UUID/GUID 랜덤 문자열을 생성합니다.
비밀 상점Secret를 반환합니다.
JSON 문자열을 Luau 테이블로 디코딩합니다.
Luau 테이블에서 JSON 문자열을 생성합니다.
URL이 안전하지 않은 문자를 '%'와 16진수 문자 두 개로 바꿉니다.
HTTP GET
- PostAsync(url : Variant,data : string,content_type : Enum.HttpContentType,compress : boolean,headers : Variant):string
HTTP POST
정보 사전을 사용하여 지정된 HTTP 메서드를 사용하여 HTTP 요청을 보냅니다.
속성
HttpEnabled
true 로 설정하면 스크립트가 HttpService:GetAsync() , HttpService:PostAsync() 및 HttpService:RequestAsync() 을 사용하여 웹사이트에 요청을 보낼 수 있습니다.
이 속성은 Studio의 게임 설정 인터페이스를 통해 전환해야 하거나, 게시되지 않은 경험을 위해 이 속성을 true을 사용하여 설정해야 합니다.
game:GetService("HttpService").HttpEnabled = true
메서드
GenerateGUID
이 메서드는 랜덤으로 모든 사용자에게 고유한 식별자(UUID) 문자열을 생성합니다.UID의 16바이트는 하이픈으로 구분된 5개의 그룹에서 32개의 16진수(기본 16) 숫자로 표시되며, 예를 들어 8-4-4-4-12 형식으로 총 36자를 나타냅니다, 예를 들어 123e4567-e89b-12d3-a456-426655440000.
사용된 UUID 사양은 버전 4(랜덤), 변형 1(DCE 1.1, ISO/IEC 11578:1996)입니다.이 버전의 UUID는 완전히 랜덤으로 생성되기 때문에 단순함으로 인해 가장 널리 사용됩니다.이 버전에는 다른 UUID 버전에 있는 특정 기능, 예를 들어 인코딩된 타임스탬프, MAC 주소 또는 시간 기반 정렬과 같은 UIDV7 또는 ULID와 같은 시간 기반 정렬이 없습니다.
103조 UID 내에서 중복을 찾을 확률이 1억 분의 1인 5.3×10 36개의 고유한 v4 UUID가 있습니다.
wrapInCurlyBraces 인수는 반환된 문자열이 굵은 괄호로 감싸져 있는지 여부를 결정합니다({}). 예를 인스턴스:
- true : {94b717b2-d54f-4340-a504-bd809ef5bf5c}
- false : db454790-7563-44ed-ab4b-397ff5df737b
매개 변수
반환된 문자열이 굵은 괄호로 감싸여야 하는지( {} ).
반환
랜덤으로 생성된 UUID.
코드 샘플
local HttpService = game:GetService("HttpService")
local result = HttpService:GenerateGUID(true)
print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58}
GetSecret
이 메서드는 경험에 이전에 추가된 값을 비밀 저장소에 반환합니다.비밀 콘텐츠는 인쇄할 수 없으며 경험이 로컬로 실행될 때 사용할 수 없습니다.
반환된 Secret 는 Secret:AddPrefix() 와 같은 내장 메서드를 사용하여 변환될 수 있습니다. HTTP 요청의 일부로 전송될 것으로 예상됩니다.
자세한 내용은 사용 가이드를 참조하십시오.
매개 변수
반환
JSONDecode
이 메서드는 JSON 개체 또는 배열을 다음 특성으로 Luau 테이블로 변환합니다:
- 테이블의 키는 문자열이나 숫자이지만 둘 다는 아닙니다. JSON 개체에 둘 다 포함되어 있으면 문자열 키가 무시됩니다.
- 빈 JSON 개체는 빈 Luau 테이블을 생성합니다({}).
- input 문자열이 유효한 JSON 개체가 아니면 이 메서드에서 오류가 발생합니다.
Luau 테이블을 JSON 개체로 인코딩하려면 HttpService:JSONEncode() 메서드를 사용하십시오.
이 메서드는 HTTP 요청이 활성화되었는지 여부에 관계없이 사용할 수 있습니다.
매개 변수
디코딩되는 JSON 개체.
반환
Luau 테이블로 디코딩된 JSON 개체.
코드 샘플
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
이 메서드는 Luau 테이블을 다음 가이드라인에 따라 JSON 개체 또는 배열로 변환합니다:
테이블의 키는 문자열이나 숫자여야 합니다. 테이블에 둘 다 포함되어 있으면 배열이 우선됩니다(문자열 키는 무시됩니다).
빈 Luau 테이블( {} )은 빈 JSON 배열을 생성합니다.
값 nil는 결코 생성되지 않습니다.
순환 테이블 참조는 오류를 발생시킵니다.
이 메서드는 유효하지 않은 JSON인 inf 및 nan와 같은 값을 허용합니다.다른 곳에서 출력된 JSON을 사용하려는 경우 문제가 발생할 수 있습니다.
인코딩 프로세스를 역방향으로 되돌리고 JSON 개체를 디코드하려면 HttpService:JSONDecode() 메서드를 사용하십시오.
이 메서드는 HTTP 요청이 활성화되었는지 여부에 관계없이 사용할 수 있습니다.
매개 변수
입력 Luau 테이블.
반환
반환된 JSON 문자열.
코드 샘플
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
이 메서드는 백분율로 인코딩 지정된 문자열을 사용하여 예약된 문자가 %와 두 개의 16진수 문자로 올바르게 인코딩되도록 합니다.
이는 HttpService:GetAsync() / HttpService:PostAsync() 를 사용하여 URL을 서식 지정할 때, 또는 POST 미디어 유형의 데이터 application/x-www-form-urlencoded (Enum.HttpContentType.ApplicationUrlEncoded)에 유용합니다.
예를 인스턴스, URL을 인코딩할 때 https://www.roblox.com/discover#/, 이 메서드는 https%3A%2F%2Fwww%2Eroblox%2Ecom%2Fdiscover%23%2F를 반환합니다.
매개 변수
인코딩할 문자열(URL).
반환
인코딩된 문자열.
코드 샘플
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
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
이 메서드는 HTTP GET단일 사전 대신 HTTP 요청 매개변수를 메서드 매개변수로 수락하고 HTTP 응답의 본문만 반환하는 것을 제외하고 기능은 RequestAsync()와 유사합니다.일반적으로 이 메서드는 약식으로만 유용하며 RequestAsync() 대부분의 경우에 사용해서는 안됩니다.
When true , the nocache 매개 변수는 이 메서드가 동일한 url 에서 이전 호출의 결과를 캐시하지 못하게 합니다.
매개 변수
데이터를 요청하는 웹 주소.
요청이 응답을 저장(캐시)하는지 여부.
일부 HTTP 요청 헤더를 지정하는 데 사용됩니다.
반환
GET 요청의 응답 신체.
코드 샘플
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
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
이 메서드는 HTTP POST단일 사전 대신 HTTP 요청 매개변수를 메서드 매개변수로 수락하고 HTTP 응답의 본문만 반환하는 것을 제외하고 기능은 RequestAsync()와 유사합니다.일반적으로 이 메서드는 약식으로만 유용하며 RequestAsync() 대부분의 경우에 사용해서는 안됩니다.
When true , the compress 매개 변수는 큰 요청 본문이 gzip 을 사용하여 압축되는지 여부를 제어합니다.
매개 변수
데이터의 대상 주소.
전송되는 데이터.
요청과 함께 전송된 Content-Type 헤더의 값을 수정합니다.
데이터가 압축되었는지( 압축됨 ) 전송할지 여부를 결정합니다.
일부 HTTP 요청 헤더를 지정하는 데 사용됩니다.
반환
요청 결과를 나타내는 HTTP 응답이 반환됩니다.
코드 샘플
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
이 메서드는 사전을 사용하여 HTTP 요청을 보내고 대상 URL, 메서드, 헤더 및 요청 본문 데이터와 같은 요청 데이터를 지정합니다.받은 응답 데이터를 설명하는 사전을 반환합니다.옵션으로, 요청은 Enum.HttpCompression를 사용하여 압축될 수 있습니다.
사전 필드 요청
<th>유형</th><th>필수</th><th>설명</th></tr></thead><tbody><tr><td><code>URL</code></td><td>문자열</td><td>예</td><td>이 요청의 대상 URL. <code>http</code> 또는 <code>https</code> 프로토콜을 사용해야 합니다.</td></tr><tr><td><code>메서드</code></td><td>문자열</td><td>no</td><td>이 요청에서 사용되는 HTTP 메서드는 대부분 <code>GET</code> 또는 <code>POST</code>입니다.</td></tr><tr><td><code>헤더</code></td><td>사전</td><td>no</td><td>이 요청에 사용할 헤더 사전. 대부분의 HTTP 헤더는 여기에서 허용되지만, 전체아닙니다.</td></tr><tr><td><code>바디</code></td><td>문자열</td><td>no</td><td>요청 본문.바이너리 신체포함하여 모든 문자열이 될 수 있습니다.<code>GET</code> 또는 <code>HEAD</code> HTTP 메서드를 사용할 때 제외해야 합니다.JSON이나 다른 형식을 전송할 때 <code>콘텐츠 유형</code> 헤더를 지정해야 할 수 있습니다.</td></tr><tr><td><code>압축</code></td><td><code>HttpCompression 열거형</code></td><td>no</td><td>요청의 데이터를 압축하는 선택적 압축 필드.값은 <code>Enum.HttpCompression.None</code> 또는 <code>Enum.HttpCompression.Gzip</code> 일 수 있습니다.</td></tr></tbody>
이름 |
---|
지원되는 HTTP 메서드
HTTP 요청 메서드는 요청 목적과 요청이 성공하면 예상되는 내용을 지정합니다.예를 인스턴스, GET 요청 메서드는 요청된 주소에 리소스를 요청하고, 성공하면 해당 주소의 리소스가 반환된다고 서버에 알립니다.마찬가지로, HEAD 요청 메서드는 서버가 Body 요소 없이 응답을 반환하도록 알고 있는 것을 제외하고 동일합니다.
<th>설명</th><th>안전</th></tr></thead><tbody><tr><td><code>가져오기</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/GET">ⓘ</a></td><td><code>GET</code> 메서드는 지정된 주소에서 리소스를 요청합니다. <code>바디</code> 매개변수 사용을 지원하지 않습니다.</td><td>예</td></tr><tr><td><code>머리</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/HEAD">ⓘ</a></td><td><code>머리</code> 메서드는 <code>가져오기</code> 요청과 동일한 응답을 요청하지만 응답 신체없습니다.<code>바디</code> 매개변수 사용을 지원하지 않습니다.</td><td>예</td></tr><tr><td><code>게시</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/POST">ⓘ</a></td><td><code>POST</code> 메서드는 제공된 <code>Body</code> 데이터를 요청된 주소에 제출합니다.</td><td>No</td></tr><tr><td><code>PUT</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PUT">ⓘ</a></td><td>PUT 메서드는 제공된 Body 데이터 내에 지정된 리소스의 모든 현재 반복을 대체합니다.</td><td>No</td></tr><tr><td><code>삭제</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/DELETE">ⓘ</a></td><td><code>삭제</code> 메서드는 요청된 주소에 제공된 <code>Body</code> 데이터에 지정된 리소스를 삭제합니다.</td><td>No</td></tr><tr><td><code>옵션</code> <a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/OPTIONS">ⓘ</a></td><td><code>옵션</code> 메서드는 제공된 주소에 대한 허용된 통신 옵션을 요청합니다.</td><td>예</td></tr><tr><td><code>추적</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/TRACE">ⓘ</a></td><td>추적 메서드는 제공된 바디 데이터에 지정된 리소스로 향하는 경로에서 메시지 루프백 테스트를 수행합니다.</td><td>예</td></tr><tr><td><code>패치</code><a href="https://developer.mozilla.org/docs/Web/HTTP/Methods/PATCH">ⓘ</a></td><td><code>패치</code> 메서드는 요청된 주소에 제공된 <code>바디</code> 데이터에 부분 변경을 적용하여 지정된 리소스에 변경 사항을 적용합니다.</td><td>No</td></tr></tbody>
메서드 |
---|
HTTP 헤더
요청 사전에서 요청에 사용할 사용자 지정 HTTP 헤더를 지정할 수 있습니다.그러나 일부 헤더는 지정할 수 없습니다.예를 들어, Content-Length는 요청 신체결정됩니다.User-Agent 및 Roblox-Id 는 Roblox에 의해 잠겨 있습니다.Accept 또는 Cache-Control와 같은 다른 헤더는 기본값을 사용하지만 재정의할 수 있습니다.일반적으로 일부 REST API는 요청 헤더에 API 키 또는 다른 서비스 인증이 지정되어야 할 수 있습니다.
RequestAsync() 메서드는 바디 콘텐츠의 형식을 감지하지 않습니다.많은 웹 서버는 특정 형식을 보내는 경우 Content-Type 헤더가 적절하게 설정되어야 합니다.다른 방법의 HttpService 사용은 Enum.HttpContentType 열거형을 사용하며, 이 방법에서는 적절하게 Content-Type 헤더를 설정합니다: text/plain , text/xml , application/xml , application/json 또는 application/x-www-form-urlencoded 는 각각의 열거형 값에 대한 교체 Content-Type 헤더 값입니다.
응답 사전 필드
RequestAsync() 는 다음 필드를 포함하는 사전을 반환합니다:
<th>유형</th><th>설명</th></tr></thead><tbody><tr><td><code>성공</code></td><td>부울</td><td>요청의 성공 상태. 이는 <code>상태 코드</code>가 범위 <code>200</code> - <code>299</code> 내에 있는 경우에만 사실입니다.</td></tr><tr><td><code>상태 코드</code></td><td>정수</td><td>응답 상태를 식별하는 HTTP 응답 코드.</td></tr><tr><td><code>상태 메시지</code></td><td>문자열</td><td>반환된 상태 메시지.</td></tr><tr><td><code>헤더</code></td><td>사전</td><td>이 응답에서 설정된 헤더 사전.</td></tr><tr><td><code>바디</code></td><td /><td>응답에서 받은 요청 본문(콘텐츠).</td></tr></tbody>
이름 |
---|
오류 사례
RequestAsync() 응답 시간이 초과되거나 대상 서버가 요청을 거부하면 오류가 발생합니다.웹 서비스가 어떤 이유로 중단되면 이 메서드를 사용하는 스크립트가 완전히 작동을 중지할 수 있습니다.필요한 정보가 없는 경우 이 메서드에 대한 호출을 pcall()로 래핑하고 오류 발생 사례를 우아하게 처리하는 것이 좋습니다.
제한
현재 HTTP 요청 전송 및 수신의 제한은 분당 500개의 요청입니다.이 임계값 이상의 요청은 실패합니다.또한 Roblox 도메인이 제외됩니다.즉, HTTP 요청을 www.roblox.com과 같은 Roblox 소유 사이트로 보낼 수 없습니다.
매개 변수
서버에서 요청할 정보가 포함된 사전입니다.
반환
지정된 서버의 응답 정보가 포함된 사전입니다.
코드 샘플
-- 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