UnityWebRequest + REST API Server 연동하기

2022. 4. 30. 17:18Network/수업 내용

 

UnityWebRequest 는 REST API Server 와 연동하기 위한 수단이다.

UnityWebRequest 를 사용하려면

using UnityEngine.Networking;을 명시해줘야 한다.

 

아래 코드는 

유니티에서 서버에 요청을 하고,

서버의 응답을 받아 유니티에서 사용하는 코드이다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Newtonsoft.Json;

public class Packets
{
    public class signup
    {
        public string email;
        public string password;
        public signup(string email, string password)
        {
            this.email = email;
            this.password = password;
        }
    }

    public class result
    {
        public int status;
        public string message;

        public result(int status, string message)
        {
            this.status = status;
            this.message = message;
        }
    }
}


public class RestAPI : MonoBehaviour
{
    public Button btnGet;
    public Button btnPost;

    // Start is called before the first frame update
    void Start()
    {
        this.btnGet.onClick.AddListener(() => {
            Debug.Log("get");
            this.StartCoroutine(this.WaitForGet());
        });
        this.btnPost.onClick.AddListener(() => {
            Debug.Log("post");
            this.StartCoroutine(this.WaitForPost());
        });
    }

    IEnumerator WaitForGet()
    {
        //UnityWebRequest객체를 만들고 
        UnityWebRequest www = UnityWebRequest.Get("http://localhost:3000/members");
        //요청을 보낸다 
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.Log("네트워크 환경이 좋지 않습니다.");
        }
        else
        {
            Debug.Log(www.downloadHandler.text);
        }
    }

    IEnumerator WaitForPost()
    {
        //통신 객체를 생성 
        UnityWebRequest www = new UnityWebRequest("http://localhost:3000/members", "POST");

        //데이터 객체를 생성 
        Packets.signup signup = new Packets.signup("lim@gmail.com", "zxc123");

        //객체를 역직렬화 
        string json = JsonConvert.SerializeObject(signup);
        Debug.Log(json);

        //문자열을 바이트 배열로 변환 
        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);

        //통신 객체 바디에 정보를 실었다 
        www.uploadHandler = new UploadHandlerRaw(bodyRaw);

        //응답객체를 담은 버퍼 
        www.downloadHandler = new DownloadHandlerBuffer();

        //헤더에 보낼 데이터의 형식을 기록 
        www.SetRequestHeader("Content-Type", "application/json");

        //요청을 보냄 
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.Log("네트워크 환경이 좋지 않습니다.");
        }
        else
        {
            Debug.Log(www.downloadHandler.text);
            Packets.result result = JsonConvert.DeserializeObject<Packets.result>(www.downloadHandler.text);
            Debug.Log(result.status);
            Debug.Log(result.message);
        }
    }
}

매핑클래스를 만들어 서버로부터 온 응답객체의 데이터를 담았다.

GET 방식과 POST 방식에 차이가 있으니 주의하자.

 

아래는 서버단 코드이다.

서버단 코드에

mysql2를 활용하면

REST API를 이용한 유니티와 데이터베이스 연동이 가능하다.

 

 

 

https://docs.unity3d.com/kr/2020.3/Manual/UnityWebRequest.html

 

UnityWebRequest - Unity 매뉴얼

UnityWebRequest는 HTTP 요청을 구성하고 HTTP 리스폰스를 처리하기 위한 모듈식 시스템을 제공합니다. UnityWebRequest 시스템의 주요 목표는 Unity 게임이 최신 웹 브라우저 백 엔드와 상호작용할 수 있도

docs.unity3d.com

 

'Network > 수업 내용' 카테고리의 다른 글

22.05.03 UnityWebView  (0) 2022.05.03