12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using UnityEngine;
- using UnityEngine.Networking;
- /* 本文件二次封装Web request
- */
- 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, Dictionary<string, string> postData=null, string filePath = null, System.Action<string> callback=null)
- {
-
- // 创建 WWWForm 对象
- WWWForm form = new WWWForm();
- // 添加access token
- bool accessTokenReq = true;
- foreach (string whiteUrl in EnviromentSetting.accessTokenWhiteList)
- {
- if (url == whiteUrl && accessTokenReq == true)
- {
- accessTokenReq = false;
- }
- }
- if (accessTokenReq) { form.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);
- form.AddBinaryData(Path.GetFileName(filePath), fileData);
- }
- // 创建 UnityWebRequest 对象
- url = EnviromentSetting.serverIp + url;
- using (UnityWebRequest request = UnityWebRequest.Post(url, form))
- {
- // 发送请求并等待响应
- yield return request.SendWebRequest();
- // 检查是否有错误
- if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
- {
- Debug.LogError("上传失败: " + request.error);
- }
- else
- {
- // 上传成功,获取服务器响应
- string responseText = request.downloadHandler.text;
- callback?.Invoke(responseText);
- Debug.Log("上传成功!服务器响应: " + responseText);
- }
- }
- }
- }
|