WebController.cs 2.3 KB

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