123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using UnityEngine;
- using UnityEngine.Networking;
- using UnityEngine.SceneManagement;
- /* 本文件二次封装Web request
- * 不需要客户端确认是否需要提交accss_token,access_token白名单在EnviromentSetting里面
- * PostRequest 需要提交url, wwwForm, 上传附件path, 回调函数
- */
- public class WebController : MonoBehaviour {
- // Start is called before the first frame update
- //void Start()
- //{
- //}
- // Update is called once per frame
- //void Update()
- //{
- //}
- public static IEnumerator PostRequest(string url, WWWForm wwwForm, string filePath = null, System.Action<string> callback=null)
- {
- // 检测是否需要添加access_token
- bool accessTokenReq = true;
- if (EnviromentSetting.accessTokenWhiteList.Contains<string>(url))
- {
- accessTokenReq = false;
- }
- //foreach (string whiteUrl in EnviromentSetting.accessTokenWhiteList)
- //{
- // if (url == whiteUrl)
- // {
- // accessTokenReq = false;
- // }
- //}
- // 添加access token
- if (accessTokenReq)
- {
- // 如果access token过期,跳转登录场景
- TimeSpan ts = DateTime.Now - EnviromentSetting.accessTokenReceivedTime;
- if (ts.TotalHours >= 24)
- {
- GameData.subScene = null;
- SceneManager.LoadScene("Login");
- }
- else
- {
- wwwForm.AddField("access_token", EnviromentSetting.accessToken);
- }
- }
-
- // 添加表单字段
- //foreach (var item in postData)
- //{
- // form.AddField(item.Key, item.Value);
- //}
- // 添加文件
- if (filePath != null)
- {
- byte[] fileData = System.IO.File.ReadAllBytes(filePath);
- wwwForm.AddBinaryData(Path.GetFileName(filePath), fileData);
- }
- // 创建 UnityWebRequest 对象
- url = EnviromentSetting.serverIp + url;
- using (UnityWebRequest request = UnityWebRequest.Post(url, wwwForm))
- {
- // 发送请求并等待响应
- yield return request.SendWebRequest();
- // 检查是否有错误
- if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
- {
- Debug.Log("上传失败: " + request.error);
- if (request.error == "Cannot connect to destination host")
- {
- string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", "network_error", EnviromentSetting.languageCode });
- MessageBoxController.ShowMessage(msg, () => Application.Quit());
- }
- Debug.Log("上传失败信息: " + request.downloadHandler.text);
- }
- else
- {
- // 上传成功,获取服务器响应
- string responseText = request.downloadHandler.text;
- callback?.Invoke(responseText);
- Debug.Log("上传成功!服务器响应: " + responseText);
- }
- }
- }
- }
|