Unity/C#

Unity Web Client

영스파파 2018. 1. 18. 16:37



using UnityEngine;

using UnityEngine.Networking;

using System.Collections;

using System.Text;

using BestHTTP;



public class Test : MonoBehaviour

{

bool _isSend = false;


// Use this for initialization

void Start()

{

StartCoroutine(CoExe());

}


IEnumerator CoExe()

{

//*

Send("http://127.0.0.1:3000/addUser/test1", "{\"password\":\"123456\",\"name\":\"789\"}", "POST");

yield return new WaitWhile(() => _isSend);

Send("http://127.0.0.1:3000/addUser/test2", "{\"password\":\"123456\",\"name\":\"789\"}", "POST");

yield return new WaitWhile(() => _isSend);

Send("http://127.0.0.1:3000/list", "", "GET");

yield return new WaitWhile(() => _isSend);


Send("http://127.0.0.1:3000/deleteUser/test1", "", "DELETE");

yield return new WaitWhile(() => _isSend);

Send("http://127.0.0.1:3000/deleteUser/test2", "", "DELETE");

yield return new WaitWhile(() => _isSend);

Send("http://127.0.0.1:3000/list", "", "GET");


yield break;

/*/

yield return StartCoroutine(CoSend("http://127.0.0.1:3000/addUser/test1", "{\"password\":\"123456\",\"name\":\"789\"}", "POST"));

yield return StartCoroutine(CoSend("http://127.0.0.1:3000/addUser/test2", "{\"password\":\"123456\",\"name\":\"789\"}", "POST"));

yield return StartCoroutine(CoSend("http://127.0.0.1:3000/list", "", "GET"));


yield return StartCoroutine(CoSend("http://127.0.0.1:3000/deleteUser/test1", "", "DELETE"));

yield return StartCoroutine(CoSend("http://127.0.0.1:3000/deleteUser/test2", "", "DELETE"));

yield return StartCoroutine(CoSend("http://127.0.0.1:3000/list", "", "GET"));

//*/

}


void Send(string url, string body, string httpMethod)

{

_isSend = true;


HTTPMethods method = HTTPMethods.Get;

switch (httpMethod)

{

case "GET":

method = HTTPMethods.Get;

break;

case "POST":

method = HTTPMethods.Post;

break;

case "PUT":

method = HTTPMethods.Put;

break;

case "DELETE":

method = HTTPMethods.Delete;

break;

}


HTTPRequest request = new HTTPRequest(new System.Uri(url), method, Ack);

request.SetHeader("Content-Type", "application/json; charset=UTF-8");


request.RawData = Encoding.UTF8.GetBytes(body);

request.Send();

}


void Ack(HTTPRequest request, HTTPResponse response)

{

if (response != null)

{

Debug.LogError(request.Uri);

Debug.LogError(response.DataAsText);

}


_isSend = false;

}


IEnumerator CoSend(string url, string body, string httpMethod)

{

var request = new UnityWebRequest(url, httpMethod);

if (!string.IsNullOrEmpty(body))

{

byte[] bodyRaw = new UTF8Encoding().GetBytes(body);

request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);

}

request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

request.SetRequestHeader("Content-Type", "application/json; charset=UTF-8");


yield return request.Send();


Debug.LogError(url);

Debug.LogError(request.downloadHandler.text);


request.Dispose();

}

}