using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.Events; using UnityEngine.Networking; /******************************************************************************** *Create By CG *Function 利用Get和Post方式进行网络请求 *********************************************************************************/ namespace ZXK.UTility { public class WebConnCtrl : MonoBehaviour { /// /// Post发送json数据 /// /// /// Json数据 /// 回调信息 /// public static IEnumerator SendPostRequestWithData(string url, string postData, UnityAction ac = null) { Debug.Log("POST请求中。。。Url:" + url); Debug.Log("数据。。。:" + postData); using (UnityWebRequest requestPost = new UnityWebRequest(url, "POST")) { byte[] postBytes = Encoding.UTF8.GetBytes(postData); requestPost.uploadHandler = new UploadHandlerRaw(postBytes); requestPost.downloadHandler = new DownloadHandlerBuffer(); requestPost.SetRequestHeader("Content-Type", "application/json"); yield return requestPost.SendWebRequest(); if (requestPost.isDone && requestPost.result!=UnityWebRequest.Result.ProtocolError) { DownloadHandler downloadHandler_TXT = requestPost.downloadHandler; Debug.Log(url + "。。。请求完成"); if (ac != null) ac(downloadHandler_TXT.text); } else { Debug.Log(url + " ERROR " + requestPost.error); } } } /// /// 发送的POST请求,提供请求成功后,针对返回值的回调接口 /// /// POST请求的路径 /// 返回值处理接口 /// public static IEnumerator SendPostRequest(string url, UnityAction ac = null) { Debug.Log("POST请求中。。。Url:" + url); using(UnityWebRequest requestPost = new UnityWebRequest(url, "POST")) { requestPost.downloadHandler = new DownloadHandlerBuffer(); yield return requestPost.SendWebRequest(); if (requestPost.isDone && requestPost.result != UnityWebRequest.Result.ProtocolError) { DownloadHandler downloadHandler_TXT = requestPost.downloadHandler; Debug.Log(url + "。。。请求完成"); if (ac != null) ac(downloadHandler_TXT.text); } else { Debug.Log(url + " ERROR " + requestPost.error); } } } /// /// 发送的GET请求,提供请求成功后,针对返回值的回调接口 /// /// Get请求 /// 返回值处理接口 /// public static IEnumerator SendGetRequestWithValue(string uriData, UnityAction ac = null) { Debug.Log("GET请求中。。。Url:" + uriData); using (UnityWebRequest requestGet = UnityWebRequest.Get(uriData)) { yield return requestGet.SendWebRequest(); if (requestGet.result == UnityWebRequest.Result.ProtocolError) { Debug.Log("————请求失败————"); Debug.Log(requestGet.downloadHandler.text); } else { Debug.Log("———请求成功———"); Debug.Log(requestGet.downloadHandler.text); if (ac != null) ac(requestGet.downloadHandler.text); } } } } }