요약
메서드
CreateWebStreamClient(streamClientType: Enum.WebStreamClientType,requestOptions: Dictionary):WebStreamClient |
GenerateGUID(wrapInCurlyBraces: boolean):string |
JSONDecode(input: string):Variant |
JSONEncode(input: Variant):string |
PostAsync(url: Variant,data: string,content_type: Enum.HttpContentType,compress: boolean,headers: Variant):string |
RequestAsync(requestOptions: Dictionary):Dictionary |
상속된 멤버
코드 샘플
우주 비행사
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- 엔드포인트 URL에 요청을 합니다
local response = HttpService:GetAsync(URL_ASTROS)
-- JSON 응답을 파싱합니다
local data = HttpService:JSONDecode(response)
-- 데이터 테이블의 정보는 응답 JSON에 따라 다릅니다
if data.message == "success" then
print("현재 우주에 있는 우주 비행사는 " .. data.number .. "명입니다:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. "은(는) " .. person.craft .. "에 있습니다")
end
end국제 우주 정거장은 어디에 있나요?
local HttpService = game:GetService("HttpService")
-- 국제 우주 정거장은 지금 어디에 있나요?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- 문제가 발생할 경우 pcall을 사용합니다
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- 우리의 요청이 실패했거나 JSON 파싱이 실패했나요?
if not data then
return false
end
-- 데이터의 유효성을 완전히 검사합니다. 이는 요청을 보내고 있는 엔드포인트에 의존합니다.
-- 이 예제의 경우 이 엔드포인트에 대해 설명합니다: 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("국제 우주 정거장은 현재 다음 위치에 있습니다:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("성공")
else
print("뭔가 잘못되었습니다")
end새로운 Pastebin 게시물
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API 개발자 키
-- https://pastebin.com/api#1
["api_dev_key"] = "당신의 API 개발자 키로 채우세요",
["api_option"] = "paste", -- "paste"로 유지
["api_paste_name"] = "HttpService:PostAsync", -- 붙여넣기 이름
["api_paste_code"] = "안녕하세요, 세계", -- 붙여넣기 내용
["api_paste_format"] = "text", -- 붙여넣기 형식
["api_paste_expire_date"] = "10M", -- 만료 날짜
["api_paste_private"] = "0", -- 0=공개, 1=비공식, 2=비공개
["api_user_key"] = "", -- 사용자 키, 비어 있으면 게스트로 게시
}
-- pastebin API는 POST 데이터에 대해 URL 인코딩된 문자열을 사용합니다
-- 다른 API는 JSON, XML 또는 다른 형식을 사용할 수 있습니다
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) -- 처음의 & 제거
-- 우리가 보내는 데이터입니다
print(data)
-- 요청을 만듭니다
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- 응답은 새 붙여넣기로 연결되는 URL입니다(또는 문제가 있으면 오류 문자열을 반환합니다)
print(response)HttpService를 통한 클라우드 열기
-- 경험 설정에서 HTTP 요청을 활성화하는 것을 잊지 마세요!
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}`, -- 사용자의 그룹 구성원을 업데이트합니다.
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- JSON을 보낼 때는 이 설정을 하세요!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Creator Hub에 설정하세요
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("응답이 성공적이었습니다:", response.StatusCode, response.StatusMessage)
else
print("응답이 오류를 반환했습니다:", response.StatusCode, response.StatusMessage)
end
print("응답 본문:\n", response.Body)
print("응답 헤더:\n", HttpService:JSONEncode(response.Headers))
end
-- 요청이 실패할 경우 스크립트가 중단되지 않도록 함수를 'pcall'로 감싸는 것을 잊지 마세요
local success, message = pcall(request)
if not success then
print("HTTP 요청 전송에 실패했습니다:", message)
endAPI 참조
속성
메서드
CreateWebStreamClient
HttpService:CreateWebStreamClient(
매개 변수
코드 샘플
HttpService CreateWebStreamClient SSE
local HttpService = game:GetService("HttpService")
local URL_GEMINI_SSE = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key="
local geminiSecret = HttpService:GetSecret("gemini_secret") -- 이미 Gemini API 키를 로컬 비밀로 업로드했다고 가정합니다.
local url_with_secret = geminiSecret:AddPrefix(URL_GEMINI_SSE) -- 플러그인은 로컬 비밀에 접근할 수 없다는 점을 기억하세요!
local function handleOpen(responseStatusCode, headers)
print("스트림이 반응 코드와 함께 열림:", responseStatusCode)
end
local function handleMessage(message)
-- 스트림 유형에 따라 이벤트를 파싱합니다.
print("스트림 메시지를 수신했습니다:", message)
end
local function request()
local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, {
Url = url_with_secret,
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- JSON을 보낼 때는 이 설정을 하세요!
},
Body = HttpService:JSONEncode({ contents = { parts = { text ="SSE 프로토콜은 어떻게 작동하나요?" }}}),
})
local openConnection = sse_client.Opened:Connect(handleOpen)
local messageConnection = sse_client.MessageReceived:Connect(handleMessage)
sse_client.Closed:Wait()
openConnection:Disconnect()
messageConnection:Disconnect()
end
-- 요청이 실패할 경우 스크립트가 중단되지 않도록 함수를 'pcall'로 감싸는 것을 기억하세요.
local success, message = pcall(request)
if not success then
print("WebStreamClient 실패:", message)
endHttpService CreateWebStreamClient RawStream
local HttpService = game:GetService("HttpService")
local LOCAL_LLM_PORT = "http://localhost:11434/api/generate?stream=true"
local function handleMessage(message)
-- 스트림 유형에 따라 이벤트를 파싱합니다.
-- 응답 Content-Type 헤더가 JSON인 경우, 이렇게 디코드할 수 있습니다:
local json = HttpService:JSONDecode(message)
end
local function handleError(responseStatusCode, errorMessage)
print("스트림 오류와 응답 코드:", responseStatusCode)
end
local function request()
local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, {
-- Ollama를 사용하여 로컬에서 실행 중인 Llama3.2 LLM 서버
Url = LOCAL_LLM_PORT,
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- JSON을 보낼 때 이걸 설정하세요!
},
Body = HttpService:JSONEncode({ model="llama3.2", prompt ="재미있는 농담 하나 해줘"}),
})
local messageConnection = sse_client.MessageReceived:Connect(handleMessage)
local errorConnection = sse_client.Error:Connect(handleError)
sse_client.Closed:Wait()
messageConnection:Disconnect()
errorConnection:Disconnect()
sse_client:close()
end
-- 요청이 실패할 경우 스크립트가 중단되지 않도록 함수를 'pcall'로 감싸는 것을 잊지 마세요.
local success, message = pcall(request)
if not success then
print("WebStreamClient 실패:", message)
endGenerateGUID
GetAsync
매개 변수
url:Variant |
| 기본값: false |
headers:Variant |
반환
코드 샘플
우주 비행사
local HttpService = game:GetService("HttpService")
local URL_ASTROS = "http://api.open-notify.org/astros.json"
-- 엔드포인트 URL에 요청을 합니다
local response = HttpService:GetAsync(URL_ASTROS)
-- JSON 응답을 파싱합니다
local data = HttpService:JSONDecode(response)
-- 데이터 테이블의 정보는 응답 JSON에 따라 다릅니다
if data.message == "success" then
print("현재 우주에 있는 우주 비행사는 " .. data.number .. "명입니다:")
for i, person in pairs(data.people) do
print(i .. ": " .. person.name .. "은(는) " .. person.craft .. "에 있습니다")
end
end국제 우주 정거장은 어디에 있나요?
local HttpService = game:GetService("HttpService")
-- 국제 우주 정거장은 지금 어디에 있나요?
local URL_ISS = "http://api.open-notify.org/iss-now.json"
local function printISS()
local response
local data
-- 문제가 발생할 경우 pcall을 사용합니다
pcall(function()
response = HttpService:GetAsync(URL_ISS)
data = HttpService:JSONDecode(response)
end)
-- 우리의 요청이 실패했거나 JSON 파싱이 실패했나요?
if not data then
return false
end
-- 데이터의 유효성을 완전히 검사합니다. 이는 요청을 보내고 있는 엔드포인트에 의존합니다.
-- 이 예제의 경우 이 엔드포인트에 대해 설명합니다: 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("국제 우주 정거장은 현재 다음 위치에 있습니다:")
print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
return true
end
end
return false
end
if printISS() then
print("성공")
else
print("뭔가 잘못되었습니다")
endJSONDecode
매개 변수
반환
Variant
코드 샘플
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
-- tab["hello"]와 tab.hello가 동일하므로,
-- 여기서 data["info"]["points"]를 사용할 수도 있습니다:
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("모든 정보:")
for key, value in pairs(data.info) do
print(key, typeof(value), value)
end
endJSONEncode
매개 변수
input:Variant |
반환
코드 샘플
HttpService JSONEncode
local HttpService = game:GetService("HttpService")
local tab = {
-- 기억하세요: 이 줄들은 같습니다
--["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)PostAsync
HttpService:PostAsync(
매개 변수
url:Variant |
| 기본값: "ApplicationJson" |
| 기본값: false |
headers:Variant |
반환
코드 샘플
새로운 Pastebin 게시물
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API 개발자 키
-- https://pastebin.com/api#1
["api_dev_key"] = "당신의 API 개발자 키로 채우세요",
["api_option"] = "paste", -- "paste"로 유지
["api_paste_name"] = "HttpService:PostAsync", -- 붙여넣기 이름
["api_paste_code"] = "안녕하세요, 세계", -- 붙여넣기 내용
["api_paste_format"] = "text", -- 붙여넣기 형식
["api_paste_expire_date"] = "10M", -- 만료 날짜
["api_paste_private"] = "0", -- 0=공개, 1=비공식, 2=비공개
["api_user_key"] = "", -- 사용자 키, 비어 있으면 게스트로 게시
}
-- pastebin API는 POST 데이터에 대해 URL 인코딩된 문자열을 사용합니다
-- 다른 API는 JSON, XML 또는 다른 형식을 사용할 수 있습니다
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) -- 처음의 & 제거
-- 우리가 보내는 데이터입니다
print(data)
-- 요청을 만듭니다
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- 응답은 새 붙여넣기로 연결되는 URL입니다(또는 문제가 있으면 오류 문자열을 반환합니다)
print(response)RequestAsync
매개 변수
코드 샘플
HTTP 요청 보내기
-- 경험 설정에서 HTTP 요청을 활성화하는 것을 잊지 마세요!
local HttpService = game:GetService("HttpService")
local function request()
local response = HttpService:RequestAsync({
Url = "http://httpbin.org/post", -- 이 웹사이트는 HTTP 요청 디버그에 도움을 줍니다
Method = "POST",
Headers = {
["Content-Type"] = "application/json", -- JSON을 보낼 때는 이 설정을 하세요!
},
Body = HttpService:JSONEncode({ hello = "world" }),
})
if response.Success then
print("상태 코드:", response.StatusCode, response.StatusMessage)
print("응답 본문:\n", response.Body)
else
print("요청이 실패했습니다:", response.StatusCode, response.StatusMessage)
end
end
-- 요청이 실패할 경우 스크립트가 중단되지 않도록 함수를 'pcall'로 감싸는 것을 잊지 마세요
local success, message = pcall(request)
if not success then
print("HTTP 요청 실패:", message)
endHttpService를 통한 클라우드 열기
-- 경험 설정에서 HTTP 요청을 활성화하는 것을 잊지 마세요!
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}`, -- 사용자의 그룹 구성원을 업데이트합니다.
Method = "PATCH",
Headers = {
["Content-Type"] = "application/json", -- JSON을 보낼 때는 이 설정을 하세요!
["x-api-key"] = HttpService:GetSecret("APIKey"), -- Creator Hub에 설정하세요
},
Body = HttpService:JSONEncode({ role = `groups/{groupId}/roles/{roleId}` }),
})
if response.Success then
print("응답이 성공적이었습니다:", response.StatusCode, response.StatusMessage)
else
print("응답이 오류를 반환했습니다:", response.StatusCode, response.StatusMessage)
end
print("응답 본문:\n", response.Body)
print("응답 헤더:\n", HttpService:JSONEncode(response.Headers))
end
-- 요청이 실패할 경우 스크립트가 중단되지 않도록 함수를 'pcall'로 감싸는 것을 잊지 마세요
local success, message = pcall(request)
if not success then
print("HTTP 요청 전송에 실패했습니다:", message)
endUrlEncode
매개 변수
반환
코드 샘플
HttpService URL 인코딩
local HttpService = game:GetService("HttpService")
local content = "Je suis allé au cinéma." -- "영화에 갔다"를 의미하는 프랑스어
local result = HttpService:UrlEncode(content)
print(result) --> Je%20suis%20all%C3%A9%20au%20cinema%2E새로운 Pastebin 게시물
local HttpService = game:GetService("HttpService")
local URL_PASTEBIN_NEW_PASTE = "https://pastebin.com/api/api_post.php"
local dataFields = {
-- Pastebin API 개발자 키
-- https://pastebin.com/api#1
["api_dev_key"] = "당신의 API 개발자 키로 채우세요",
["api_option"] = "paste", -- "paste"로 유지
["api_paste_name"] = "HttpService:PostAsync", -- 붙여넣기 이름
["api_paste_code"] = "안녕하세요, 세계", -- 붙여넣기 내용
["api_paste_format"] = "text", -- 붙여넣기 형식
["api_paste_expire_date"] = "10M", -- 만료 날짜
["api_paste_private"] = "0", -- 0=공개, 1=비공식, 2=비공개
["api_user_key"] = "", -- 사용자 키, 비어 있으면 게스트로 게시
}
-- pastebin API는 POST 데이터에 대해 URL 인코딩된 문자열을 사용합니다
-- 다른 API는 JSON, XML 또는 다른 형식을 사용할 수 있습니다
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) -- 처음의 & 제거
-- 우리가 보내는 데이터입니다
print(data)
-- 요청을 만듭니다
local response = HttpService:PostAsync(URL_PASTEBIN_NEW_PASTE, data, Enum.HttpContentType.ApplicationUrlEncoded, false)
-- 응답은 새 붙여넣기로 연결되는 URL입니다(또는 문제가 있으면 오류 문자열을 반환합니다)
print(response)