JsonUploader.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. using Newtonsoft.Json;
  6. using System.Text;
  7. using System;
  8. public class JsonUploader.cs : BaseSceneManager<JsonUploader>
  9. {
  10. private const string authURL = @"http://192.168.10.211:4050/auth/student";
  11. // ==================================================
  12. public void Auth(string value) => StartCoroutine(AuthAction(value));
  13. private IEnumerator AuthAction(string value)
  14. {
  15. AuthData authData = new AuthData();
  16. authData.internalId = value;
  17. string json = JsonConvert.SerializeObject(authData);
  18. // 上传json的方法
  19. // 上传bytes否则jsonbody会被误作为head
  20. using (UnityWebRequest www = new UnityWebRequest(authURL, UnityWebRequest.kHttpVerbPOST))
  21. {
  22. www.SetRequestHeader("Content-Type", "application/json");
  23. www.SetRequestHeader("Accept", "application/json");
  24. byte[] bytes = Encoding.UTF8.GetBytes(json);
  25. www.uploadHandler = new UploadHandlerRaw(bytes);
  26. DownloadHandler downloadHandler = new DownloadHandlerBuffer();
  27. www.downloadHandler = downloadHandler;
  28. yield return www.SendWebRequest();
  29. if (www.result != UnityWebRequest.Result.Success)
  30. {
  31. Debug.Log($"{www.error}...<color=red>[ER]</color>");
  32. yield break;
  33. }
  34. else
  35. {
  36. Debug.Log(www.downloadHandler.text);
  37. ResponAuthData responAuthData = JsonConvert.DeserializeObject<ResponAuthData>(www.downloadHandler.text.ToString());
  38. if (responAuthData.code == 0)
  39. {
  40. PlayerManager.Instance.SetPlayerPrefsStudentID(value);
  41. }
  42. else
  43. {
  44. }
  45. }
  46. }
  47. yield break;
  48. }
  49. // ==================================================
  50. [Serializable]
  51. public class AuthData
  52. {
  53. public string internalId;
  54. }
  55. [Serializable]
  56. public class ResponAuthData
  57. {
  58. public int code;
  59. public string data;
  60. }
  61. }