using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Security.Cryptography; using XRTool.Util; using LitJson; using System; using System.Text; using UnityEngine.Networking; using System.Linq; using System.IO; using System.Net.Http; public class NetWorkHeaders : MonoBehaviour { private List queue; private static bool init; public static NetWorkHeaders Instance; public static string MD5STR = "sTuDi0jH7FlCgd"; void Awake() { if (!init) { init = true; Instance = this; queue = new List(); DontDestroyOnLoad(this.gameObject); } else { Destroy(this.gameObject); return; } } /// /// Adds the network. /// /// Action. /// Data. /// Type. /// Success fun. /// Failed fun. public void AddNetwork(string action, JsonData data, Action successFun = null, Action failedFun = null) { Network net = new Network(); net.init(action, data, successFun, failedFun); queue.Add(net); checkQueue(); } void checkQueue() { // UnityLog.Log("networkQueueCount: " + queue.Count); if (queue.Count == 0) { return; } if (queue[0].active) { return; } StartCoroutine(post(queue[0])); } IEnumerator post(Network net) { //CommonMethod.ShowNetLoading("NetWork","通讯中..."); net.active = true; string url = net.action; JsonData form = net.data; byte[] postBytes = System.Text.Encoding.Default.GetBytes(form.ToJson()); //UnityLog.Log("token===>" + UserInfo.Token); UnityWebRequest www = new UnityWebRequest(url, "POST"); www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes); www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); // www.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded"); www.SetRequestHeader("Content-Type", "application/json"); www.SetRequestHeader("unionId", UserInfo.UnionId); www.SetRequestHeader("token", UserInfo.User_Token); // www.uploadHandler =new UploadHandlerRaw(body); // WWW www = new WWW(url, form); UnityLog.Log("url: " + www.url); UnityLog.Log("param: " + net.data.ToJson()); yield return www.SendWebRequest();//等待Web服务器的反应 //CommonMethod.HideNetLoading("NetWork"); string result = string.Empty; if (www.error != null) { result = www.error; Debug.Log("networkError: " + result); postError("1009"); } else if(www.isDone) { result = www.downloadHandler.text; UnityLog.Log("networkSuccess: " + result); postSuccess(result); } queue.RemoveAt(0); checkQueue(); } void postSuccess(string postData) { JsonData data = null; string code = ""; Debug.Log(postData); try { data = JsonMapper.ToObject(postData); code = data["code"].ToString(); } catch (Exception e) { Debug.Log(e.Data); postError("1009"); } switch (code) { case "200": queue[0].scuess(data); break; default: UnityLog.Log("error"); //if (data["message"].ToString() == "vaild account") //{ // //PlayerPrefs.SetString(UserInfo.Account, ""); //} queue[0].failed(postData); break; } } void postError(string errorData) { queue[0].error(errorData); } public void getNetTexture(string action, WWWForm data, Action success = null) { StartCoroutine(LoadTextureFromLocal(action, data, success)); } //读取纹理 IEnumerator LoadTextureFromLocal(string action, WWWForm data = null, Action success = null) { UnityLog.Log("tupian123................" + action); WWW w; if (data != null) w = new WWW(action, data); else w = new WWW(action); yield return w; if (w.isDone) { // Material material = new Material(Shader.Find("Unlit/Texture")); // material.mainTexture = w.texture; if (success != null) success(w.texture); } } Dictionary keyValues = new Dictionary(); public void Upload(string cert, string path, Action success = null) { // string url = "https://webapi-fat.shadowcreator.com/100032/file/uploads"; string url = "https://support.ghz-tech.com:8843/api//file/uploads"; string result; string[] arr = path.Split('/'); string filename = arr[arr.Length - 1]; string[] arr1 = filename.Split('.'); string fileType = arr1[arr1.Length - 1]; if (fileType == "mp4" || fileType == "png" || fileType == "jpg" || fileType == "jpeg") { keyValues.Add("cert", cert); result = PostJsonData(url, keyValues, path, filename); keyValues.Clear(); path = ""; test.path = ""; success?.Invoke(result); } else { return; } } public void Upload(string cert, byte[] bytes, Action success = null) { string url = "https://support.ghz-tech.com:8843/api//file/uploads"; string result; keyValues.Add("cert", cert); string fileName = "YCXZ_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".png"; result = PostJsonData(url, keyValues, bytes, fileName); keyValues.Clear(); bytes = null; SaveShot.bytes = null; success?.Invoke(result); } /// /// MD5码 /// /// /// public static string MD5Encrypt(string strText) { MD5 md5 = MD5.Create(); byte[] fromData = Encoding.Default.GetBytes(strText); byte[] targetData = md5.ComputeHash(fromData); StringBuilder byte2String = new StringBuilder(); for (int i = 0; i < targetData.Length; i++) { byte2String.AppendFormat("{0:x2}", targetData[i]); } return byte2String.ToString(); } public static string FieldToString(JsonData data) { Dictionary dic = new Dictionary(); foreach (string key in data.Keys) { dic.Add(key, data[key].ToString()); } string str = ""; int count = 0; Dictionary dicDesc = dic.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value); foreach (string kvp in dicDesc.Keys) { count++; if (data.Keys.Count <= count) { str = str + kvp + "=" + data[kvp]; } else { str = str + kvp + "=" + data[kvp] + "&"; } } return str + MD5STR; } public static void SendHttp(JsonData jsonData, Action success = null, Action failed = null) { //Dictionary data = new Dictionary(); //foreach (string key in jsonData.Keys) //{ // data.Add(key, jsonData[key].ToString()); //} //#if BUILDTYPE_RELEASE || BUILDTYPE_TEST // data.Add("sign", "588cd263bfd7a7b5e561dba46b989ef1"); // //string md5 = MD5Encrypt(MD5Encrypt(FieldToString(jsonData))); // //Debug.Log(md5); // //data.AddField("sign", md5); //#endif //#if BUILDTYPE_DEBUG // // data.AddField("sign", "588cd263bfd7a7b5e561dba46b989ef1"); // string md5 = MD5Encrypt(MD5Encrypt(FieldToString(jsonData))); // Debug.Log(md5); // data.Add("sign", md5); //#endif string action = NetWorkHeadersConfig.Remote_Net_url+ jsonData["action"].ToString(); NetWorkHeaders.Instance.AddNetwork(action, jsonData, success, failed); } /// /// 账号密码登录 /// /// /// /// /// public static void Login(string account, string password, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/account/login"; jsdata["account"] = account; jsdata["deviceid"] = DeviceInfo.SN; jsdata["devicetype"] = DeviceInfo.MODEL; jsdata["deviceos"] = DeviceInfo.RELEASE_VERSION; jsdata["password"] = password; jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString(); UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 预登陆 /// /// /// /// /// public static void YuLogin(string account, string password, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/account/advance"; jsdata["account"] = account; jsdata["deviceid"] = DeviceInfo.SN; jsdata["devicetype"] = DeviceInfo.MODEL; jsdata["deviceos"] = DeviceInfo.RELEASE_VERSION; jsdata["password"] = password; jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString(); // UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 预登陆,需要验证码 /// /// /// /// /// public static void YuLogin(string account, string password, string captcha, string captchaId, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/account/advance"; jsdata["Account"] = account; jsdata["captcha"] = captcha; jsdata["captchaId"] = captchaId; jsdata["deviceid"] = DeviceInfo.SN; jsdata["devicetype"] = DeviceInfo.MODEL; jsdata["deviceos"] = DeviceInfo.RELEASE_VERSION; jsdata["password"] = password; jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString(); UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 账号密码登录,需要验证码 /// /// /// /// /// public static void GetUserInfo(Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/user/userInfo"; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } public static void Activate(string license, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/account/activate"; jsdata["unionId"] = UserInfo.UnionId; jsdata["token"] = UserInfo.User_Token; jsdata["license"] = license; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 账号密码登录,需要验证码 /// /// /// /// /// public static void SetUserInfo(Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/user/profile"; jsdata["nickName"] = UserInfo.userName; jsdata["avatar"] = UserInfo.avatar; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 账号密码登录,需要验证码 /// /// /// /// /// public static void GetUserAvater(Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/common/avatar"; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 账号密码登录,需要验证码 /// /// /// /// /// public static void SetUserSys(bool mic,bool camera,int resolution, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/settings/modify"; jsdata["mic"] = mic; jsdata["camera"] = camera; jsdata["resolution"] = resolution; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 发送验证码 /// /// /// /// public static void SendVerifycode(string phone,Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "10001"; jsdata["code_type"] = "1"; jsdata["phone"] = phone; jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString(); UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 手机验证登录 /// /// /// /// /// public static void PhoneLogin(string phone, string code, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/account/phoneLogin"; jsdata["phone"] = phone; jsdata["code"] = code; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } public static void YuPhoneLogin(string phone, Action success = null, Action failed = null) { JsonData jsdata = new JsonData(); jsdata["action"] = "/account/phoneAdvance"; jsdata["phone"] = phone; UnityLog.Log(jsdata.ToJson()); SendHttp(jsdata, success, failed); } /// /// 获取图形验证码 /// /// /// public static void GetTextureCode(Action success = null, Action failed = null) { JsonData jsonData = new JsonData(); jsonData["action"] = "/account/captcha"; jsonData["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString(); // NetWorkHeaders.Instance.getNetTexture(action, data, success); // NetWorkHeaders.Instance.AddNetwork(action, data, success, failed); SendHttp(jsonData, success, failed); } /// /// 上传文件 /// /// <服务器地址> /// /// <文件的本地储存地址> /// <文件的名字> /// public static string PostJsonData(string url, Dictionary dic, string filepath, string filename) { string str = ""; try { HttpClient client = new HttpClient(); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); postContent.Headers.Add("unionId", UserInfo.UnionId); postContent.Headers.Add("token", UserInfo.User_Token); string filekeyname = "file"; postContent.Add(new ByteArrayContent(File.ReadAllBytes(filepath)), filekeyname, filename); foreach (var key in dic.Keys) { postContent.Add(new StringContent(dic[key].ToString()), key); } HttpResponseMessage response = client.PostAsync(url, postContent).Result; str = response.Content.ReadAsStringAsync().Result; } catch (Exception ex) { Debug.LogError("PostJsonData:" + ex.ToString()); } return str; } public static string PostJsonData(string url, Dictionary dic, byte[] bytes, string filename) { string str = ""; try { HttpClient client = new HttpClient(); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); postContent.Headers.Add("unionId", UserInfo.UnionId); postContent.Headers.Add("token", UserInfo.User_Token); string filekeyname = "file"; postContent.Add(new ByteArrayContent(bytes), filekeyname, filename); foreach (var key in dic.Keys) { postContent.Add(new StringContent(dic[key].ToString()), key); } HttpResponseMessage response = client.PostAsync(url, postContent).Result; str = response.Content.ReadAsStringAsync().Result; } catch (Exception ex) { Debug.LogError("PostJsonData:" + ex.ToString()); } return str; } }