70 lines
2.8 KiB
C#
70 lines
2.8 KiB
C#
using BestHTTP;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using UnityEngine;
|
|
|
|
public class Request<T>
|
|
{
|
|
public int status { get; set; }
|
|
|
|
private bool is_end = false;
|
|
public bool get_id_end { get { return is_end; } }
|
|
|
|
/// <summary>
|
|
/// 데이터를 송수신해야할 때 사용합니다. send()는 생성을 마치고 자동으로 보냅니다.
|
|
/// </summary>
|
|
/// <typeparam name="T">역직렬화할 타입</typeparam>
|
|
/// <param name="API">api 주소</param>
|
|
/// <param name="onRequestFinished">데이터 받은 후 처리할 절차</param>
|
|
/// <param name="serializeData">전송할 데이터, null로 넣으면 안보냅니다.</param>
|
|
/// <param name="methods">동작방식</param>
|
|
/// <param name="codec">암복호화 할 것인지</param>
|
|
/// <returns>역직렬화된 데이터 or 기본값(반환 받지 못함)</returns>
|
|
/// Json에러가 발생할경우 packageManager > + > add package by name > name : com.unity.nuget.newtonsoft-json 추가
|
|
public HTTPRequest CreateRequest(Protocol protocol, Action<T> onRequestFinished, object serializeData, HTTPMethods methods = HTTPMethods.Post, Action errorRequestFinished = null)
|
|
{
|
|
string API = $"{Statics.url}".Replace("\\p{Z}", String.Empty);
|
|
#if UNITY_EDITOR
|
|
Debug.Log(API);
|
|
#endif
|
|
var httpRquest = new HTTPRequest(new Uri(API) //url 넣기
|
|
, methods //동작 방식 넣기
|
|
, (request, response) => {
|
|
if (response == null //알 수 없는 문제
|
|
|| (response.StatusCode < 200 && response.StatusCode > 299) //성공 외 반환
|
|
|| string.IsNullOrEmpty(response.DataAsText)) //서버에서 반환 데이터 없음
|
|
//|| response.DataAsText.Contains("error")) //서버에서 처리 중 에러 반환
|
|
{
|
|
Debug.LogError("status : " + response.StatusCode);
|
|
|
|
if (errorRequestFinished != null)
|
|
{
|
|
errorRequestFinished();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
#if UNITY_EDITOR
|
|
Debug.Log(response.DataAsText);
|
|
#endif
|
|
T deSerialized = JsonConvert.DeserializeObject<T>(response.DataAsText);
|
|
onRequestFinished(deSerialized);
|
|
}
|
|
});
|
|
|
|
if (serializeData != null)
|
|
{
|
|
httpRquest.SetHeader("Content-Type", "application/json");
|
|
httpRquest.SetHeader("cmd", ((int)protocol).ToString());
|
|
string json = JsonConvert.SerializeObject(serializeData);
|
|
#if UNITY_EDITOR
|
|
Debug.Log($"<color=white>{json.Substring(0, Mathf.Min(json.Length, 15000))}</color>");
|
|
#endif
|
|
httpRquest.RawData = System.Text.Encoding.UTF8.GetBytes(json);
|
|
}
|
|
|
|
httpRquest.Send();
|
|
return httpRquest;
|
|
}
|
|
}
|