using UnityEngine; using LitJson; using System; using System.Collections; using System.Collections.Generic; public class URLRequest : MonoBehaviour { public enum Method { GET, POST, } public string url; public Method method; public WWWForm form; public URLRequestCallBackDelegate callBack; public URLRequestJsonCallBackDelegate jsonCallBack; // Use this for initialization IEnumerator Start() { WWW www = (form == null ? new WWW(url) : new WWW(url, form)); yield return www; string data = null; Debuger.LogWarning("Url loaded : "+url); if(www.error != null) { data = www.error; Debuger.LogError("Url error : "+www.error); } else { data = www.text; Debuger.LogWarning("Url result : "+www.text); } if(callBack != null) callBack(data); if(jsonCallBack != null) jsonCallBack(ParseRecieveJsonData(data)); Destroy(this.gameObject); } public delegate void URLRequestCallBackDelegate(string data); public delegate void URLRequestJsonCallBackDelegate(JsonData data); public static URLRequest CreateStrURLRequest(string url, URLRequestData data = null, URLRequestCallBackDelegate callBack = null, Method method = Method.GET, bool dataEye = false) { URLRequest urlRequest = CreateBaseURLRequest(url, data, method, dataEye); urlRequest.callBack = callBack; return urlRequest; } public static URLRequest CreateURLRequest(string url, URLRequestData data = null, URLRequestJsonCallBackDelegate callBack = null, Method method = Method.GET) { URLRequest urlRequest = CreateBaseURLRequest(url, data, method); urlRequest.jsonCallBack = callBack; return urlRequest; } private static URLRequest CreateBaseURLRequest(string url, URLRequestData requestData = null, Method method = Method.GET, bool dataEye = false) { GameObject gameObj = new GameObject("URLRequest"); URLRequest urlRequest = gameObj.AddComponent(); Debuger.Log("Url request : "+url); if(!dataEye && requestData.HasData()) { if(method == Method.GET) { if(url.IndexOf("?") == -1) url += "?"; if(url.Substring(url.Length-1) != "?") url += "&"; url += requestData.GetDataString(); } else if(method == Method.POST) { urlRequest.form = requestData.GetDataForm(); } } urlRequest.url = url; return urlRequest; } public static JsonData ParseRecieveJsonData(string data) { int index = data.IndexOf("{"); if(index >= 0) { data = data.Substring(index); } try { return JsonMapper.ToObject(data); } catch(JsonException e) { Debuger.LogException(e); } JsonData json = new JsonData(); json["error"] = 0; return json; } }