using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public static class InterfaceManager { private static string _IP; public static string IP { get { return _IP; } set { if (_IP != value) { _IP = value; } } } private static string _Port; public static string Port { get { return _Port; } set { if (_Port!=value) { _Port = value; } } } public static string IpAddress { get => string.Format("http://{0}:{1}", IP, Port);} public static string GetLocalTxt(string path) { using (System.IO.StreamReader reader = new System.IO.StreamReader(path)) { return reader.ReadToEnd(); } } public static IEnumerator Getbytes(string url,Action callback) { using(UnityWebRequest www = new UnityWebRequest(url)) { yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.ConnectionError||www.result == UnityWebRequest.Result.ProtocolError) { callback(null); Debug.LogError("网络请求失败了"); } else { if (!string.IsNullOrEmpty(www.downloadHandler.text)) { callback(www.downloadHandler.text); } else { callback(null); Debug.Log("没有获取到数据"); } } } } /// /// Get网络请求 /// /// 路径 /// 方法回调 /// public static IEnumerator Getstring(string url,Action callback) { using(UnityWebRequest www = UnityWebRequest.Get(url)) { yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.ConnectionError|| www.result == UnityWebRequest.Result.ProtocolError) { callback(null); Debug.LogError("网络请求失败了"); } else { if (!string.IsNullOrEmpty(www.downloadHandler.text)) { callback(www.downloadHandler.text); } else { callback(null); Debug.Log("没有获取到数据"); } } } } /// /// Get每隔一段时间请求一下 /// /// 请求路径 /// 每隔多长时间请求一下 /// 回调方法 /// public static IEnumerator Getstring(string url,int tiem,Action callback) { while (true) { using(UnityWebRequest www = UnityWebRequest.Get(url)) { yield return new WaitForSeconds(tiem); yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError) { callback(null); Debug.LogError("网络请求失败了"); } else { if (!string.IsNullOrEmpty(www.downloadHandler.text)) { callback(www.downloadHandler.text); } else { callback(null); Debug.Log("没有请求到数据"); } } } } } /// /// post的请求接口 /// /// 路径 /// 字典方式传入值 /// 回调方法 /// public static IEnumerator Poststring(string url, Dictionary keyvaluepir, Action callback) { WWWForm wWWForm = new WWWForm(); foreach (var item in keyvaluepir) { wWWForm.AddField(item.Key,item.Value); } UnityWebRequest www = UnityWebRequest.Post(url,wWWForm); yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.ConnectionError||www.result == UnityWebRequest.Result.ProtocolError) { callback(false,null); Debug.LogError("网络请求失败了"); } else { if (!string.IsNullOrEmpty(www.downloadHandler.text)) { callback(true, www.downloadHandler.text); } else { callback(false, null); Debug.Log("没有请求到数据"); } } } }