WebController.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. using UnityEngine.SceneManagement;
  8. /* 本文件二次封装Web request
  9. * 不需要客户端确认是否需要提交accss_token,access_token白名单在EnviromentSetting里面
  10. * PostRequest 需要提交url, wwwForm, 上传附件path, 回调函数
  11. */
  12. public class WebController : MonoBehaviour {
  13. // Start is called before the first frame update
  14. //void Start()
  15. //{
  16. //}
  17. // Update is called once per frame
  18. //void Update()
  19. //{
  20. //}
  21. public static IEnumerator PostRequest(string url, WWWForm wwwForm, string filePath = null, System.Action<string> callback=null)
  22. {
  23. // 检测是否需要添加access_token
  24. bool accessTokenReq = true;
  25. foreach (string whiteUrl in EnviromentSetting.accessTokenWhiteList)
  26. {
  27. if (url == whiteUrl && accessTokenReq == true)
  28. {
  29. accessTokenReq = false;
  30. }
  31. }
  32. // 添加access token
  33. if (accessTokenReq)
  34. {
  35. // 如果access token过期,跳转登录场景
  36. TimeSpan ts = DateTime.Now - EnviromentSetting.accessTokenReceivedTime;
  37. if (ts.TotalHours >= 24)
  38. {
  39. GameData.subScene = null;
  40. SceneManager.LoadScene("Login");
  41. }
  42. else
  43. {
  44. wwwForm.AddField("access_token", EnviromentSetting.accessToken);
  45. }
  46. }
  47. // 添加表单字段
  48. //foreach (var item in postData)
  49. //{
  50. // form.AddField(item.Key, item.Value);
  51. //}
  52. // 添加文件
  53. if (filePath != null)
  54. {
  55. byte[] fileData = System.IO.File.ReadAllBytes(filePath);
  56. wwwForm.AddBinaryData(Path.GetFileName(filePath), fileData);
  57. }
  58. // 创建 UnityWebRequest 对象
  59. url = EnviromentSetting.serverIp + url;
  60. using (UnityWebRequest request = UnityWebRequest.Post(url, wwwForm))
  61. {
  62. // 发送请求并等待响应
  63. yield return request.SendWebRequest();
  64. // 检查是否有错误
  65. if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
  66. {
  67. Debug.LogError("上传失败: " + request.error);
  68. }
  69. else
  70. {
  71. // 上传成功,获取服务器响应
  72. string responseText = request.downloadHandler.text;
  73. callback?.Invoke(responseText);
  74. Debug.Log("上传成功!服务器响应: " + responseText);
  75. }
  76. }
  77. }
  78. }