WebController.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. /* 本文件二次封装Web request
  7. */
  8. public class WebController : MonoBehaviour {
  9. // Start is called before the first frame update
  10. //void Start()
  11. //{
  12. //}
  13. // Update is called once per frame
  14. //void Update()
  15. //{
  16. //}
  17. public static IEnumerator PostRequest(string url, Dictionary<string, string> postData=null, string filePath = null, System.Action<string> callback=null)
  18. {
  19. // 创建 WWWForm 对象
  20. WWWForm form = new WWWForm();
  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. if (accessTokenReq) { form.AddField("access_token", EnviromentSetting.accessToken); }
  31. // 添加表单字段
  32. foreach (var item in postData)
  33. {
  34. form.AddField(item.Key, item.Value);
  35. }
  36. // 添加文件
  37. if (filePath != null)
  38. {
  39. byte[] fileData = System.IO.File.ReadAllBytes(filePath);
  40. form.AddBinaryData(Path.GetFileName(filePath), fileData);
  41. }
  42. // 创建 UnityWebRequest 对象
  43. url = EnviromentSetting.serverIp + url;
  44. using (UnityWebRequest request = UnityWebRequest.Post(url, form))
  45. {
  46. // 发送请求并等待响应
  47. yield return request.SendWebRequest();
  48. // 检查是否有错误
  49. if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
  50. {
  51. Debug.LogError("上传失败: " + request.error);
  52. }
  53. else
  54. {
  55. // 上传成功,获取服务器响应
  56. string responseText = request.downloadHandler.text;
  57. callback?.Invoke(responseText);
  58. Debug.Log("上传成功!服务器响应: " + responseText);
  59. }
  60. }
  61. }
  62. }