123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526 |
- 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<Network> 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<Network>();
- DontDestroyOnLoad(this.gameObject);
- }
- else
- {
- Destroy(this.gameObject);
- return;
- }
- }
- /// <summary>
- /// Adds the network.
- /// </summary>
- /// <param name="action">Action.</param>
- /// <param name="data">Data.</param>
- /// <param name="type">Type.</param>
- /// <param name="successFun">Success fun.</param>
- /// <param name="failedFun">Failed fun.</param>
- public void AddNetwork(string action, JsonData data, Action<JsonData> successFun = null, Action<string> 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<Texture> success = null)
- {
- StartCoroutine(LoadTextureFromLocal(action, data, success));
- }
- //读取纹理
- IEnumerator LoadTextureFromLocal(string action, WWWForm data = null, Action<Texture> 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<string, string> keyValues = new Dictionary<string, string>();
- public void Upload(string cert, string path, Action<string> 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<string> 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);
- }
- /// <summary>
- /// MD5码
- /// </summary>
- /// <param name="strText"></param>
- /// <returns></returns>
- 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<string, string> dic = new Dictionary<string, string>();
- foreach (string key in data.Keys)
- {
- dic.Add(key, data[key].ToString());
- }
- string str = "";
- int count = 0;
- Dictionary<string, string> 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<JsonData> success = null, Action<string> failed = null)
- {
- //Dictionary<string, string> data = new Dictionary<string, string>();
- //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);
- }
- /// <summary>
- /// 账号密码登录
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void Login(string account, string password, Action<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 预登陆
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void YuLogin(string account, string password, Action<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 预登陆,需要验证码
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void YuLogin(string account, string password, string captcha, string captchaId, Action<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 账号密码登录,需要验证码
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void GetUserInfo(Action<JsonData> success = null, Action<string> 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<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 账号密码登录,需要验证码
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void SetUserInfo(Action<JsonData> success = null, Action<string> 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);
- }
-
- /// <summary>
- /// 账号密码登录,需要验证码
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void GetUserAvater(Action<JsonData> success = null, Action<string> failed = null)
- {
- JsonData jsdata = new JsonData();
- jsdata["action"] = "/common/avatar";
- UnityLog.Log(jsdata.ToJson());
- SendHttp(jsdata, success, failed);
- }
- /// <summary>
- /// 账号密码登录,需要验证码
- /// </summary>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void SetUserSys(bool mic,bool camera,int resolution, Action<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 发送验证码
- /// </summary>
- /// <param name="phone"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void SendVerifycode(string phone,Action<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 手机验证登录
- /// </summary>
- /// <param name="phone"></param>
- /// <param name="code"></param>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void PhoneLogin(string phone, string code, Action<JsonData> success = null, Action<string> 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<JsonData> success = null, Action<string> failed = null)
- {
- JsonData jsdata = new JsonData();
- jsdata["action"] = "/account/phoneAdvance";
- jsdata["phone"] = phone;
- UnityLog.Log(jsdata.ToJson());
- SendHttp(jsdata, success, failed);
- }
- /// <summary>
- /// 获取图形验证码
- /// </summary>
- /// <param name="success"></param>
- /// <param name="failed"></param>
- public static void GetTextureCode(Action<JsonData> success = null, Action<string> 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);
- }
- /// <summary>
- /// 上传文件
- /// </summary>
- /// <param name="url"><服务器地址>
- /// <param name="dic"></param>
- /// <param name="filepath"><文件的本地储存地址>
- /// <param name="filename"><文件的名字>
- /// <returns></returns>
- public static string PostJsonData(string url, Dictionary<string, string> 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<string, string> 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;
- }
- }
|