Creator Guide
Korean
Korean
  • OVERDARE
    • 🚩OVERDARE 소개
    • 🐤시작하기
      • OVERDARE App
      • OVERDARE Studio
    • 📌운영 정책
      • 커뮤니티 가이드라인
      • UGC 콘텐츠 제작 가이드라인
      • UGC의 외부 활용 가이드라인
      • LOGO 활용 가이드라인
      • 지식 재산권 정책
      • 신고 안내
      • 콘텐츠 제재 이의 신청 안내
      • 크리에이터 정산 정책
      • OVERDARE 수익화 가이드라인
    • 🅰️OVERDARE Glossary
  • MANUAL
    • 🏰스튜디오 메뉴얼
      • 시작하기
        • 스튜디오 인터페이스
        • 월드 템플릿
        • 좌표계
        • 스튜디오 테스트 플레이
        • 월드 퍼블리시
        • Collaboration
      • 에셋 & 리소스 제작
        • 에셋 임포트
        • 애니메이션 에디터
      • 게임 제작
        • 게임 설정
        • 스크립트 에디터
        • 정렬
        • Material Manager
        • Collision Groups
        • Tag Editor
        • 퍼포먼스 가이드
        • 월드 성능 분석
      • Object
        • 파트
        • 모델
        • 카메라
        • 물리
        • 조명
        • Tool
        • VFX
        • Sound
      • 캐릭터
        • 캐릭터 애니메이션
        • Humanoid Description
      • GUI
    • 📝스크립트 메뉴얼
      • 시작하기
        • 스크립트 개요
        • 루아 기초 가이드
        • 코딩 스타일
        • 오브젝트 참조
        • 유니티 개발자용 가이드
      • 이벤트 및 통신
        • 이벤트
        • 서버-클라 통신
        • BindableEvent
        • Value Objects
      • 입력 및 조작
        • 모바일 조작 처리
        • TPS Strafing System
      • 게임 고도화
        • Saving & Loading Data
        • 트윈
        • 모듈 스크립트
        • JSON과 HTTP 통신
      • 디버깅 & 최적화
        • 중단점
        • 스크립트 최적화 실전 가이드
    • 💡크리에이터 참고 자료
      • 크리에이터를 위한 게임 용어 번역표
    • 💸수익화
      • Payout Guideline
  • DEVELOPMENT
    • 📚API Reference
      • Enums
        • ActuatorRelativeTo
        • AnimationPriority
        • AspectType
        • AssetTypeVerification
        • BorderMode
        • CameraMode
        • CameraType
        • ContextActionResult
        • CoreGuiType
        • DominantAxis
        • EasingDirection
        • EasingStyle
        • ForceLimitMode
        • HttpCompression
        • HttpContentType
        • HumanoidDisplayDistanceType
        • HumanoidStateType
        • KeyCode
        • Material
        • MaterialPattern
        • NormalId
        • ParticleEmitterShape
        • ParticleEmitterShapeInOut
        • ParticleEmitterShapeStyle
        • ParticleFlipbookLayout
        • ParticleFlipbookMode
        • ParticleOrientation
        • PartType
        • PlaybackState
        • RaycastFilterType
        • RollOffMode
        • RotationType
        • UserInputState
        • UserInputType
        • VelocityConstraintMode
      • DataTypes
        • BlendSpaceSampleSata
        • BrickColor
        • CFrame
        • Color3
        • ColorSequence
        • ColorSequenceKeypoint
        • Content
        • Enum
        • EnumItem
        • NumberRange
        • NumberSequence
        • NumberSequenceKeypoint
        • OverlapParams
        • PhysicalProperties
        • Ray
        • RaycastParams
        • RaycastResult
        • ScriptConnection
        • ScriptSignal
        • TweenInfo
        • Udim
        • Udim2
        • Vector2
        • Vector3
      • Classes
        • Animation
        • AngularVelocity
        • AnimationTrack
        • Animator
        • Atmosphere
        • Attachment
        • Backpack
        • BackpackItem
        • BasePart
        • BaseScript
        • Beam
        • BindableEvent
        • BlendSpace
        • BoolValue
        • Bone
        • Camera
        • CharacterMesh
        • CollectionService
        • Constraint
        • ContextActionService
        • CoreGui
        • DataStore
        • DataModel
        • DataStoreGetOptions
        • DataStoreIncrementOptions
        • DataStoreInfo
        • DataStoreKeyPages
        • DataStoreKeyInfo
        • DataStoreService
        • DataStoreListingPages
        • DataStoreSetOptions
        • FormFactorPart
        • Frame
        • Folder
        • GlobalDataStore
        • GuiBase2d
        • GuiButton
        • GuiObject
        • HttpService
        • Humanoid
        • HumanoidDescription
        • ImageButton
        • ImageLabel
        • InputObject
        • IntValue
        • LayerCollector
        • Instance
        • Light
        • Lighting
        • LinearVelocity
        • LocalScript
        • LuaSourceContainer
        • MaterialService
        • MaterialVariant
        • MeshPart
        • Model
        • ModuleScript
        • Mouse
        • NumberValue
        • OrderedDataStore
        • Pages
        • Part
        • ParticleEmitter
        • PhysicsService
        • Player
        • PlayerGui
        • Players
        • PlayerScripts
        • PointLight
        • PVInstance
        • ReplicatedStorage
        • RemoteEvent
        • ScreenGui
        • RunService
        • Script
        • ServerStorage
        • ServiceProvider
        • Skeleton
        • ServerScriptService
        • Sound
        • SoundService
        • SoundGroup
        • SpotLight
        • SpawnLocation
        • StarterCharacterScripts
        • StarterPack
        • StarterGui
        • StarterPlayer
        • StarterPlayerScripts
        • StringValue
        • SurfaceGui
        • SurfaceGuiBase
        • Team
        • Teams
        • TextLabel
        • TextButton
        • Tool
        • Trail
        • Tween
        • TweenService
        • TweenBase
        • UIAspectRatioConstraint
        • UserGameSettings
        • UserInputService
        • UserSettings
        • VectorForce
        • Workspace
        • WrapLayer
        • WorldRoot
        • WrapTarget
  • UPDATE
    • 📰Release Note
Powered by GitBook
On this page
  • 개요
  • 사용 방법
  • URL에서 응답 받기
  • URL에 JSON 데이터 보내고 응답 받기
  • URL에서 응답 받은 JSON 데이터 활용하기
  • 주의사항
  1. MANUAL
  2. 스크립트 메뉴얼
  3. 게임 고도화

JSON과 HTTP 통신

개요

HttpService를 사용하면 외부 Http 서버와 통신할 수 있습니다. 외부 API 서버에서 데이터를 가져와 월드에 활용하거나, 데이터를 외부 API 서버로 보낸 후 응답받은 데이터를 월드에 활용할 수 있습니다.

사용 방법

기능
설명

GetAsync(url)

url의 응답 받기

PostAsync(url, data)

url로 data를 보내고 응답 받기

JSONEncode(tableData)

table 형식의 tableData를 JSON string 형태로 변환 및 반환

JSONDecode(json)

JSON 형식의 JSON을 table 형태로 변환 및 반환

URL에서 응답 받기

baseUrl 변수에 입력된 url 링크에 HTTP GET 요청을 보내고 응답을 받아 response 변수에 저장하고 print하는 예시 코드입니다.

-- HttpService 불러오기
local HttpService = game:GetService("HttpService")
local baseUrl = "HTTP URL을 입력하세요"

local success, errorMessageOrResult, response = nil, nil, nil

local function HttpGet()
    -- 비동기 요청이 실패하거나 오류가 발생할 수 있으므로 pcall()로 예외 처리
    success, errorMessageOrResult = pcall(function()
        -- "baseUrl" 주소로 HTTP GET 요청을 보낸 후 받은 응답을 "response" 변수에 저장
        response = HttpService:GetAsync(baseUrl)
    end)
    
    local messageSuccess = string.format("success: %s", success)
    local messageErrorOrResult = string.format("errorMessageOrResult: %s", errorMessageOrResult)
    local messageResponse = string.format("response: %s", response)
    
    print("messageSuccess: ", messageSuccess)
    print("messageErrorOrResult: ", messageErrorOrResult)
    print("messageResponse: ", messageResponse)
end

URL에 JSON 데이터 보내고 응답 받기

baseUrl 변수에 입력된 url 링크에 월드에서 사용하던 table 데이터를 JSON으로 인코딩하여 HTTP POST 요청을 보내고 응답을 받아 response 변수에 저장하고 print하는 예시 코드입니다.

-- HttpService 불러오기
local HttpService = game:GetService("HttpService")
local baseUrl = "HTTP URL을 입력하세요"

local success, errorMessageOrResult, response = nil, nil, nil

local function HttpPost()
    -- URL로 보낼 데이터 정의
    local data = 
    {
        ["message"] = "Hello OVERDARE!",
        ["data"] = 10,
    }

    -- data를 JSON으로 인코딩
    local jsonData = HttpService:JSONEncode(data)

    -- 비동기 요청이 실패하거나 오류가 발생할 수 있으므로 pcall()로 예외 처리
    success, errorMessageOrResult = pcall(function()
        -- "baseUrl" 주소로 "jsonData" 데이터와 함께 HTTP POST 요청을 보낸 후 받은 응답을 "response" 변수에 저장
        response = HttpService:PostAsync(baseUrl, jsonData)
    end)

    local messageSuccess = string.format("success: %s", success)
    local messageErrorOrResult = string.format("errorMessageOrResult: %s", errorMessageOrResult)
    local messageResponse = string.format("response: %s", response)
    
    print("messageSuccess: ", messageSuccess)
    print("messageErrorOrResult: ", messageErrorOrResult)
    print("messageResponse: ", messageResponse)
end

URL에서 응답 받은 JSON 데이터 활용하기

baseUrl 변수에 입력된 url 링크에 HTTP GET 요청을 보내고 응답을 받아 response 변수에 저장하고 응답받은 데이터가 JSON이라는 가정 하에 table로 Decoding한 후 print하는 예시 코드입니다.

-- HttpService 불러오기
local HttpService = game:GetService("HttpService")
local baseUrl = "HTTP URL을 입력하세요"

local success, errorMessageOrResult, response = nil, nil, nil

local function HttpGetApplication()
    -- 비동기 요청이 실패하거나 오류가 발생할 수 있으므로 pcall()로 예외 처리
    success, errorMessageOrResult = pcall(function()
        -- "baseUrl" 주소로 HTTP GET 요청을 보낸 후 받은응답을 "response" 변수에 저장
        response = HttpService:GetAsync(baseUrl)
        -- JSON 문자열을 디코딩하여 table 형식으로 "response" 변수에 저장
        response = HttpService:JSONDecode(response)
    end)

    local messageSuccess = string.format("success: %s", success)
    local messageErrorOrResult = string.format("errorMessageOrResult: %s", errorMessageOrResult)
    local messageResponse = string.format("response.data: %s", response.data)
    
    print("messageSuccess: ", messageSuccess)
    print("messageErrorOrResult: ", messageErrorOrResult)
    print("messageResponse: ", messageResponse)
end

주의사항

사용하시는 API 주소 마다 분당 요청 수 등의 제한이 있을 수 있습니다. 원하는 기능 구현에 있어 반드시 해당 API 주소의 요청 수를 확인하시기 바랍니다.

Previous모듈 스크립트Next디버깅 & 최적화

Last updated 2 days ago

📝