# HttpService

HttpService : `Instance`

## Overview

외부 웹 서비스와의 통신을 위한 HTTP 요청 기능을 제공합니다. 이를 활용하면 분석 시스템 연동, 클라우드 기반 데이터 처리, 외부 서버 환경 설정 반영, 실시간 데이터 전송 등 다양한 기능을 월드에 통합할 수 있습니다.

또한 JSON 형식을 사용하는 API와 교류할 때 JSONEncode 및 JSONDecode 메서드를 통해 데이터를 간단히 직렬화하거나 역직렬화할 수 있습니다.

안정적이고 안전한 월드 환경을 유지하기 위해, 반드시 신뢰성과 보안성이 검증된 외부 플랫폼에만 HTTP 요청을 전송할 것을 권장합니다.

## Properties

### HttpEnabled

`bool`

HttpService를 통해 외부 웹 서비스와 통신할 수 있도록 허용하는 설정입니다.

이 값을 true로 지정하면 스크립트에서 GetAsync, PostAsync, RequestAsync 메서드를 사용하여 외부 서버로 HTTP 요청을 전송할 수 있습니다.

해당 옵션은 스튜디오의 Game Settings 메뉴에서도 활성화할 수 있습니다.

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")

print(HttpService.HttpEnabled)
```

## Methods

### GenerateGUID

실행 환경 전체에서 단 한 번만 UUID 문자열을 생성하며, 이후 모든 호출에서 동일한 UUID를 반환합니다.

생성된 식별자는 16바이트의 데이터를 32개의 16진수 문자로 표현한 뒤, 8-4-4-4-12 형태로 구분하여 총 36자의 문자열 형태(예: 123e4567-e89b-12d3-a456-426655440000)로 제공합니다.

#### Parameters

| `bool` bInWrapInCurlyBraces | 문자열 앞뒤에 중괄호를 포함할지 여부입니다. (기본값: false) |
| --------------------------- | ------------------------------------- |

#### Return

| `string` | 생성된 UUID입니다. |
| -------- | ------------ |

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")
local Result = HttpService:GenerateGUID(false)

print(Result)
```

### GetAsync

HTTP GET 요청을 전송하는 간단한 사용 방식으로, RequestAsync와 비슷하게 동작하지만 요청 정보를 개별 인자로 전달하고 응답 데이터 중 본문만 반환합니다. 따라서 편의상 빠르게 GET 요청을 보내야 할 때 적합하며, 보다 정교한 제어가 필요한 경우에는 RequestAsync를 사용하는 것이 더 바람직합니다.

NoCache 값을 true로 지정하면 동일한 주소로 보낸 과거 요청의 캐시를 사용하지 않고, 매번 새롭게 서버에 요청을 전송하도록 동작합니다.

#### Parameters

| `string` InUrl    | 요청할 웹 서버의 URL입니다.         |
| ----------------- | ------------------------- |
| `bool` InNoCache  | 캐시 사용 여부입니다. (기본값: false) |
| `Value` InHeaders | HTTP 요청에 포함할 헤더 정보입니다.    |

#### Return

| `string` | GET 요청에 대해 서버가 반환한 응답 데이터입니다. |
| -------- | ----------------------------- |

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")
local baseUrl = "HTTP URL을 입력하세요"

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

success, errorMessageOrResult = pcall(function()
    response = HttpService:GetAsync(baseUrl)
end)

print("Success : ", success)
print("ErrorMessageOrResult : ", errorMessageOrResult)
print("Response : ", response)
```

### JSONDecode

JSON 형식의 객체 또는 배열을 Lua 테이블로 변환합니다.

JSON 객체는 문자열 키 기반의 테이블로, JSON 배열은 1부터 시작하는 숫자 키 기반의 배열 형태로 변환됩니다.

모든 숫자는 부동소수(float) 값으로 해석되며, 중첩된 구조는 재귀적으로 변환됩니다.

비어 있는 JSON 객체나 배열은 빈 테이블로 반환됩니다.

#### Parameters

| `string` InInput | 변환할 JSON 형식의 데이터입니다. |
| ---------------- | -------------------- |

#### Return

| `Value` | 변환된 Lua 테이블 데이터입니다. |
| ------- | ------------------- |

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")

local data = HttpService:JSONDecode(jsonData)
print(data)
```

### JSONEncode

Lua 테이블을 JSON 객체 또는 배열로 변환합니다.

nil 값은 JSON에 포함되지 않으며, inf와 nan 같은 특수 숫자도 변환되지만 이는 JSON 표준에 속하지 않기 때문에 외부 시스템과 연동할 때 호환성 문제가 생길 수 있습니다.&#x20;

비어 있는 테이블은 빈 JSON 배열로 변환되며, 테이블 내부에 순환 참조가 존재할 경우 변환 과정에서 오류가 발생합니다.

#### Parameters

| `Value` InInput | 변환할 Lua 테이블 데이터입니다. |
| --------------- | ------------------- |

#### Return

| `string` | 변환된 JSON 형식의 데이터입니다. |
| -------- | -------------------- |

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")

local data = 
{
    ["message"] = "Hello OVERDARE!",
    ["data"] = 10,
}
local jsonData = HttpService:JSONEncode(data)
```

### PostAsync

HTTP POST 요청을 수행합니다. RequestAsync() 함수와 유사한 기능을 제공하지만, 요청 데이터를 하나의 딕셔너리가 아닌 개별 매개변수로 전달할 수 있으며, 응답 전체가 아닌 본문(body)만 반환합니다.

주로 간편한 코드 작성용으로 사용되며, 대부분의 상황에서는 RequestAsync() 함수를 사용하는 것이 더 바람직합니다.

또한 compress 옵션을 true로 설정하면, 대용량 요청 본문이 자동으로 gzip 형식으로 압축되어 전송 효율을 향상시킬 수 있습니다.

#### Parameters

| `string` InUrl                       | 요청할 웹 서버의 URL입니다.                                                 |
| ------------------------------------ | ----------------------------------------------------------------- |
| `string` InData                      | 전송할 데이터입니다.                                                       |
| `Enum.HttpContentType` InContentType | Content-Type 헤더 값을 조정하여 전송 형식을 지정할 수 있습니다. (기본값: ApplicationJson) |
| `bool` InCompress                    | 데이터를 서버로 보낼 때 gzip 방식으로 압축 전송을 사용할지 여부입니다. (기본값: false)           |
| `Value` InHeaders                    | HTTP 요청에 포함할 헤더 정보입니다.                                            |

#### Return

| `string` | POST 요청에 대해 서버가 반환한 응답 데이터입니다. |
| -------- | ------------------------------ |

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")
local baseUrl = "HTTP URL을 입력하세요"

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

success, errorMessageOrResult = pcall(function()
    local data = 
    {
        ["message"] = "Hello OVERDARE!",
        ["data"] = 10,
    }
    local jsonData = HttpService:JSONEncode(data)

    local contentType = Enum.HttpContentType.ApplicationJson
    local compress = false
    local headers = {}
    response = HttpService:PostAsync(baseUrl, jsonData, contentType, compress, headers)
end)

print("Success : ", success)
print("ErrorMessageOrResult : ", errorMessageOrResult)
print("Response : ", response)
```

### RequestAsync

Sends an HTTP request using any method with the provided dictionary of information.

#### Parameters

| `Dictionary` InRequestOptions |   |
| ----------------------------- | - |

#### Return

| `Value` |   |
| ------- | - |

#### Code Samples

### UrlEncode

입력된 문자열 내의 예약 문자를 % 기호와 두 자리 16진수 코드로 변환하여, URL에서 안전하게 사용할 수 있는 퍼센트 인코딩(percent-encoding) 문자열을 생성합니다.

#### Parameters

| `string` InInput | 변환할 문자열(주소)입니다. |
| ---------------- | --------------- |

#### Return

| `string` | 변환된 문자열(주소)입니다. |
| -------- | --------------- |

#### Code Samples

```lua
local HttpService = game:GetService("HttpService")

local Query = "Hello #OVERDARE#"
local Encoded = HttpService:UrlEncode(Query)

print(Encoded)
```

## Events

## See also

{% content-ref url="../../../manual/script-manual/events-and-communication/json-and-http" %}
[json-and-http](https://docs.overdare.com/korean/manual/script-manual/events-and-communication/json-and-http)
{% endcontent-ref %}
