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();
}
}
'Unity > C#' 카테고리의 다른 글
Debug 교체 (0) | 2016.03.17 |
---|---|
Partial 클래스 정의(C# 프로그래밍 가이드) (0) | 2011.06.17 |