123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- 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<URLRequest>();
- 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);
- //Debug.Log(e.ToString());
- //Debug.Log(data);
- }
-
- JsonData json = new JsonData();
- json["error"] = 0;
- return json;
- }
- }
|