NetWorkHeaders.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Security.Cryptography;
  5. using XRTool.Util;
  6. using LitJson;
  7. using System;
  8. using System.Text;
  9. using UnityEngine.Networking;
  10. using System.Linq;
  11. using System.IO;
  12. using System.Net.Http;
  13. public class NetWorkHeaders : MonoBehaviour
  14. {
  15. private List<Network> queue;
  16. private static bool init;
  17. public static NetWorkHeaders Instance;
  18. public static string MD5STR = "sTuDi0jH7FlCgd";
  19. void Awake()
  20. {
  21. if (!init)
  22. {
  23. init = true;
  24. Instance = this;
  25. queue = new List<Network>();
  26. DontDestroyOnLoad(this.gameObject);
  27. }
  28. else
  29. {
  30. Destroy(this.gameObject);
  31. return;
  32. }
  33. }
  34. /// <summary>
  35. /// Adds the network.
  36. /// </summary>
  37. /// <param name="action">Action.</param>
  38. /// <param name="data">Data.</param>
  39. /// <param name="type">Type.</param>
  40. /// <param name="successFun">Success fun.</param>
  41. /// <param name="failedFun">Failed fun.</param>
  42. public void AddNetwork(string action, JsonData data, Action<JsonData> successFun = null, Action<string> failedFun = null)
  43. {
  44. Network net = new Network();
  45. net.init(action, data, successFun, failedFun);
  46. queue.Add(net);
  47. checkQueue();
  48. }
  49. void checkQueue()
  50. {
  51. // UnityLog.Log("networkQueueCount: " + queue.Count);
  52. if (queue.Count == 0)
  53. {
  54. return;
  55. }
  56. if (queue[0].active)
  57. {
  58. return;
  59. }
  60. StartCoroutine(post(queue[0]));
  61. }
  62. IEnumerator post(Network net)
  63. {
  64. //CommonMethod.ShowNetLoading("NetWork","通讯中...");
  65. net.active = true;
  66. string url = net.action;
  67. JsonData form = net.data;
  68. byte[] postBytes = System.Text.Encoding.Default.GetBytes(form.ToJson());
  69. //UnityLog.Log("token===>" + UserInfo.Token);
  70. UnityWebRequest www = new UnityWebRequest(url, "POST");
  71. www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
  72. www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  73. // www.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  74. www.SetRequestHeader("Content-Type", "application/json");
  75. www.SetRequestHeader("unionId", UserInfo.UnionId);
  76. www.SetRequestHeader("token", UserInfo.User_Token);
  77. // www.uploadHandler =new UploadHandlerRaw(body);
  78. // WWW www = new WWW(url, form);
  79. UnityLog.Log("url: " + www.url);
  80. UnityLog.Log("param: " + net.data.ToJson());
  81. yield return www.SendWebRequest();//等待Web服务器的反应
  82. //CommonMethod.HideNetLoading("NetWork");
  83. string result = string.Empty;
  84. if (www.error != null)
  85. {
  86. result = www.error;
  87. Debug.Log("networkError: " + result);
  88. postError("1009");
  89. }
  90. else if(www.isDone)
  91. {
  92. result = www.downloadHandler.text;
  93. UnityLog.Log("networkSuccess: " + result);
  94. postSuccess(result);
  95. }
  96. queue.RemoveAt(0);
  97. checkQueue();
  98. }
  99. void postSuccess(string postData)
  100. {
  101. JsonData data = null;
  102. string code = "";
  103. Debug.Log(postData);
  104. try
  105. {
  106. data = JsonMapper.ToObject(postData);
  107. code = data["code"].ToString();
  108. }
  109. catch (Exception e)
  110. {
  111. Debug.Log(e.Data);
  112. postError("1009");
  113. }
  114. switch (code)
  115. {
  116. case "200":
  117. queue[0].scuess(data);
  118. break;
  119. default:
  120. UnityLog.Log("error");
  121. //if (data["message"].ToString() == "vaild account")
  122. //{
  123. // //PlayerPrefs.SetString(UserInfo.Account, "");
  124. //}
  125. queue[0].failed(postData);
  126. break;
  127. }
  128. }
  129. void postError(string errorData)
  130. {
  131. queue[0].error(errorData);
  132. }
  133. public void getNetTexture(string action, WWWForm data, Action<Texture> success = null)
  134. {
  135. StartCoroutine(LoadTextureFromLocal(action, data, success));
  136. }
  137. //读取纹理
  138. IEnumerator LoadTextureFromLocal(string action, WWWForm data = null, Action<Texture> success = null)
  139. {
  140. UnityLog.Log("tupian123................" + action);
  141. WWW w;
  142. if (data != null)
  143. w = new WWW(action, data);
  144. else
  145. w = new WWW(action);
  146. yield return w;
  147. if (w.isDone)
  148. {
  149. // Material material = new Material(Shader.Find("Unlit/Texture"));
  150. // material.mainTexture = w.texture;
  151. if (success != null)
  152. success(w.texture);
  153. }
  154. }
  155. Dictionary<string, string> keyValues = new Dictionary<string, string>();
  156. public void Upload(string cert, string path, Action<string> success = null)
  157. {
  158. // string url = "https://webapi-fat.shadowcreator.com/100032/file/uploads";
  159. string url = "https://support.ghz-tech.com:8843/api//file/uploads";
  160. string result;
  161. string[] arr = path.Split('/');
  162. string filename = arr[arr.Length - 1];
  163. string[] arr1 = filename.Split('.');
  164. string fileType = arr1[arr1.Length - 1];
  165. if (fileType == "mp4" || fileType == "png" || fileType == "jpg" || fileType == "jpeg")
  166. {
  167. keyValues.Add("cert", cert);
  168. result = PostJsonData(url, keyValues, path, filename);
  169. keyValues.Clear();
  170. path = "";
  171. test.path = "";
  172. success?.Invoke(result);
  173. }
  174. else
  175. {
  176. return;
  177. }
  178. }
  179. public void Upload(string cert, byte[] bytes, Action<string> success = null)
  180. {
  181. string url = "https://support.ghz-tech.com:8843/api//file/uploads";
  182. string result;
  183. keyValues.Add("cert", cert);
  184. string fileName = "YCXZ_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".png";
  185. result = PostJsonData(url, keyValues, bytes, fileName);
  186. keyValues.Clear();
  187. bytes = null;
  188. SaveShot.bytes = null;
  189. success?.Invoke(result);
  190. }
  191. /// <summary>
  192. /// MD5码
  193. /// </summary>
  194. /// <param name="strText"></param>
  195. /// <returns></returns>
  196. public static string MD5Encrypt(string strText)
  197. {
  198. MD5 md5 = MD5.Create();
  199. byte[] fromData = Encoding.Default.GetBytes(strText);
  200. byte[] targetData = md5.ComputeHash(fromData);
  201. StringBuilder byte2String = new StringBuilder();
  202. for (int i = 0; i < targetData.Length; i++)
  203. {
  204. byte2String.AppendFormat("{0:x2}", targetData[i]);
  205. }
  206. return byte2String.ToString();
  207. }
  208. public static string FieldToString(JsonData data)
  209. {
  210. Dictionary<string, string> dic = new Dictionary<string, string>();
  211. foreach (string key in data.Keys)
  212. {
  213. dic.Add(key, data[key].ToString());
  214. }
  215. string str = "";
  216. int count = 0;
  217. Dictionary<string, string> dicDesc = dic.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
  218. foreach (string kvp in dicDesc.Keys)
  219. {
  220. count++;
  221. if (data.Keys.Count <= count)
  222. {
  223. str = str + kvp + "=" + data[kvp];
  224. }
  225. else
  226. {
  227. str = str + kvp + "=" + data[kvp] + "&";
  228. }
  229. }
  230. return str + MD5STR;
  231. }
  232. public static void SendHttp(JsonData jsonData, Action<JsonData> success = null, Action<string> failed = null)
  233. {
  234. //Dictionary<string, string> data = new Dictionary<string, string>();
  235. //foreach (string key in jsonData.Keys)
  236. //{
  237. // data.Add(key, jsonData[key].ToString());
  238. //}
  239. //#if BUILDTYPE_RELEASE || BUILDTYPE_TEST
  240. // data.Add("sign", "588cd263bfd7a7b5e561dba46b989ef1");
  241. // //string md5 = MD5Encrypt(MD5Encrypt(FieldToString(jsonData)));
  242. // //Debug.Log(md5);
  243. // //data.AddField("sign", md5);
  244. //#endif
  245. //#if BUILDTYPE_DEBUG
  246. // // data.AddField("sign", "588cd263bfd7a7b5e561dba46b989ef1");
  247. // string md5 = MD5Encrypt(MD5Encrypt(FieldToString(jsonData)));
  248. // Debug.Log(md5);
  249. // data.Add("sign", md5);
  250. //#endif
  251. string action = NetWorkHeadersConfig.Remote_Net_url+ jsonData["action"].ToString();
  252. NetWorkHeaders.Instance.AddNetwork(action, jsonData, success, failed);
  253. }
  254. /// <summary>
  255. /// 账号密码登录
  256. /// </summary>
  257. /// <param name="account"></param>
  258. /// <param name="password"></param>
  259. /// <param name="success"></param>
  260. /// <param name="failed"></param>
  261. public static void Login(string account, string password, Action<JsonData> success = null, Action<string> failed = null)
  262. {
  263. JsonData jsdata = new JsonData();
  264. jsdata["action"] = "/account/login";
  265. jsdata["account"] = account;
  266. jsdata["deviceid"] = DeviceInfo.SN;
  267. jsdata["devicetype"] = DeviceInfo.MODEL;
  268. jsdata["deviceos"] = DeviceInfo.RELEASE_VERSION;
  269. jsdata["password"] = password;
  270. jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString();
  271. UnityLog.Log(jsdata.ToJson());
  272. SendHttp(jsdata, success, failed);
  273. }
  274. /// <summary>
  275. /// 预登陆
  276. /// </summary>
  277. /// <param name="account"></param>
  278. /// <param name="password"></param>
  279. /// <param name="success"></param>
  280. /// <param name="failed"></param>
  281. public static void YuLogin(string account, string password, Action<JsonData> success = null, Action<string> failed = null)
  282. {
  283. JsonData jsdata = new JsonData();
  284. jsdata["action"] = "/account/advance";
  285. jsdata["account"] = account;
  286. jsdata["deviceid"] = DeviceInfo.SN;
  287. jsdata["devicetype"] = DeviceInfo.MODEL;
  288. jsdata["deviceos"] = DeviceInfo.RELEASE_VERSION;
  289. jsdata["password"] = password;
  290. jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString();
  291. // UnityLog.Log(jsdata.ToJson());
  292. SendHttp(jsdata, success, failed);
  293. }
  294. /// <summary>
  295. /// 预登陆,需要验证码
  296. /// </summary>
  297. /// <param name="account"></param>
  298. /// <param name="password"></param>
  299. /// <param name="success"></param>
  300. /// <param name="failed"></param>
  301. public static void YuLogin(string account, string password, string captcha, string captchaId, Action<JsonData> success = null, Action<string> failed = null)
  302. {
  303. JsonData jsdata = new JsonData();
  304. jsdata["action"] = "/account/advance";
  305. jsdata["Account"] = account;
  306. jsdata["captcha"] = captcha;
  307. jsdata["captchaId"] = captchaId;
  308. jsdata["deviceid"] = DeviceInfo.SN;
  309. jsdata["devicetype"] = DeviceInfo.MODEL;
  310. jsdata["deviceos"] = DeviceInfo.RELEASE_VERSION;
  311. jsdata["password"] = password;
  312. jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString();
  313. UnityLog.Log(jsdata.ToJson());
  314. SendHttp(jsdata, success, failed);
  315. }
  316. /// <summary>
  317. /// 账号密码登录,需要验证码
  318. /// </summary>
  319. /// <param name="account"></param>
  320. /// <param name="password"></param>
  321. /// <param name="success"></param>
  322. /// <param name="failed"></param>
  323. public static void GetUserInfo(Action<JsonData> success = null, Action<string> failed = null)
  324. {
  325. JsonData jsdata = new JsonData();
  326. jsdata["action"] = "/user/userInfo";
  327. UnityLog.Log(jsdata.ToJson());
  328. SendHttp(jsdata, success, failed);
  329. }
  330. public static void Activate(string license, Action<JsonData> success = null, Action<string> failed = null)
  331. {
  332. JsonData jsdata = new JsonData();
  333. jsdata["action"] = "/account/activate";
  334. jsdata["unionId"] = UserInfo.UnionId;
  335. jsdata["token"] = UserInfo.User_Token;
  336. jsdata["license"] = license;
  337. UnityLog.Log(jsdata.ToJson());
  338. SendHttp(jsdata, success, failed);
  339. }
  340. /// <summary>
  341. /// 账号密码登录,需要验证码
  342. /// </summary>
  343. /// <param name="account"></param>
  344. /// <param name="password"></param>
  345. /// <param name="success"></param>
  346. /// <param name="failed"></param>
  347. public static void SetUserInfo(Action<JsonData> success = null, Action<string> failed = null)
  348. {
  349. JsonData jsdata = new JsonData();
  350. jsdata["action"] = "/user/profile";
  351. jsdata["nickName"] = UserInfo.userName;
  352. jsdata["avatar"] = UserInfo.avatar;
  353. UnityLog.Log(jsdata.ToJson());
  354. SendHttp(jsdata, success, failed);
  355. }
  356. /// <summary>
  357. /// 账号密码登录,需要验证码
  358. /// </summary>
  359. /// <param name="account"></param>
  360. /// <param name="password"></param>
  361. /// <param name="success"></param>
  362. /// <param name="failed"></param>
  363. public static void GetUserAvater(Action<JsonData> success = null, Action<string> failed = null)
  364. {
  365. JsonData jsdata = new JsonData();
  366. jsdata["action"] = "/common/avatar";
  367. UnityLog.Log(jsdata.ToJson());
  368. SendHttp(jsdata, success, failed);
  369. }
  370. /// <summary>
  371. /// 账号密码登录,需要验证码
  372. /// </summary>
  373. /// <param name="account"></param>
  374. /// <param name="password"></param>
  375. /// <param name="success"></param>
  376. /// <param name="failed"></param>
  377. public static void SetUserSys(bool mic,bool camera,int resolution, Action<JsonData> success = null, Action<string> failed = null)
  378. {
  379. JsonData jsdata = new JsonData();
  380. jsdata["action"] = "/settings/modify";
  381. jsdata["mic"] = mic;
  382. jsdata["camera"] = camera;
  383. jsdata["resolution"] = resolution;
  384. UnityLog.Log(jsdata.ToJson());
  385. SendHttp(jsdata, success, failed);
  386. }
  387. /// <summary>
  388. /// 发送验证码
  389. /// </summary>
  390. /// <param name="phone"></param>
  391. /// <param name="success"></param>
  392. /// <param name="failed"></param>
  393. public static void SendVerifycode(string phone,Action<JsonData> success = null, Action<string> failed = null)
  394. {
  395. JsonData jsdata = new JsonData();
  396. jsdata["action"] = "10001";
  397. jsdata["code_type"] = "1";
  398. jsdata["phone"] = phone;
  399. jsdata["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString();
  400. UnityLog.Log(jsdata.ToJson());
  401. SendHttp(jsdata, success, failed);
  402. }
  403. /// <summary>
  404. /// 手机验证登录
  405. /// </summary>
  406. /// <param name="phone"></param>
  407. /// <param name="code"></param>
  408. /// <param name="success"></param>
  409. /// <param name="failed"></param>
  410. public static void PhoneLogin(string phone, string code, Action<JsonData> success = null, Action<string> failed = null)
  411. {
  412. JsonData jsdata = new JsonData();
  413. jsdata["action"] = "/account/phoneLogin";
  414. jsdata["phone"] = phone;
  415. jsdata["code"] = code;
  416. UnityLog.Log(jsdata.ToJson());
  417. SendHttp(jsdata, success, failed);
  418. }
  419. public static void YuPhoneLogin(string phone, Action<JsonData> success = null, Action<string> failed = null)
  420. {
  421. JsonData jsdata = new JsonData();
  422. jsdata["action"] = "/account/phoneAdvance";
  423. jsdata["phone"] = phone;
  424. UnityLog.Log(jsdata.ToJson());
  425. SendHttp(jsdata, success, failed);
  426. }
  427. /// <summary>
  428. /// 获取图形验证码
  429. /// </summary>
  430. /// <param name="success"></param>
  431. /// <param name="failed"></param>
  432. public static void GetTextureCode(Action<JsonData> success = null, Action<string> failed = null)
  433. {
  434. JsonData jsonData = new JsonData();
  435. jsonData["action"] = "/account/captcha";
  436. jsonData["requesttime"] = CommonMethod.GetCurrentTimeUnix().ToString();
  437. // NetWorkHeaders.Instance.getNetTexture(action, data, success);
  438. // NetWorkHeaders.Instance.AddNetwork(action, data, success, failed);
  439. SendHttp(jsonData, success, failed);
  440. }
  441. /// <summary>
  442. /// 上传文件
  443. /// </summary>
  444. /// <param name="url"><服务器地址>
  445. /// <param name="dic"></param>
  446. /// <param name="filepath"><文件的本地储存地址>
  447. /// <param name="filename"><文件的名字>
  448. /// <returns></returns>
  449. public static string PostJsonData(string url, Dictionary<string, string> dic, string filepath, string filename)
  450. {
  451. string str = "";
  452. try
  453. {
  454. HttpClient client = new HttpClient();
  455. var postContent = new MultipartFormDataContent();
  456. string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
  457. postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
  458. postContent.Headers.Add("unionId", UserInfo.UnionId);
  459. postContent.Headers.Add("token", UserInfo.User_Token);
  460. string filekeyname = "file";
  461. postContent.Add(new ByteArrayContent(File.ReadAllBytes(filepath)), filekeyname, filename);
  462. foreach (var key in dic.Keys)
  463. {
  464. postContent.Add(new StringContent(dic[key].ToString()), key);
  465. }
  466. HttpResponseMessage response = client.PostAsync(url, postContent).Result;
  467. str = response.Content.ReadAsStringAsync().Result;
  468. }
  469. catch (Exception ex)
  470. {
  471. Debug.LogError("PostJsonData:" + ex.ToString());
  472. }
  473. return str;
  474. }
  475. public static string PostJsonData(string url, Dictionary<string, string> dic, byte[] bytes, string filename)
  476. {
  477. string str = "";
  478. try
  479. {
  480. HttpClient client = new HttpClient();
  481. var postContent = new MultipartFormDataContent();
  482. string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
  483. postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
  484. postContent.Headers.Add("unionId", UserInfo.UnionId);
  485. postContent.Headers.Add("token", UserInfo.User_Token);
  486. string filekeyname = "file";
  487. postContent.Add(new ByteArrayContent(bytes), filekeyname, filename);
  488. foreach (var key in dic.Keys)
  489. {
  490. postContent.Add(new StringContent(dic[key].ToString()), key);
  491. }
  492. HttpResponseMessage response = client.PostAsync(url, postContent).Result;
  493. str = response.Content.ReadAsStringAsync().Result;
  494. }
  495. catch (Exception ex)
  496. {
  497. Debug.LogError("PostJsonData:" + ex.ToString());
  498. }
  499. return str;
  500. }
  501. }