Unity3D网络通讯(三)-- HttpRestful请求的简单封装
学更好的别人,
做更好的自己。
——《微卡智享》
前言
实现思路
微卡智享
实现Http请求的封装,我们主要考虑的就是两个问题:
所有的网络通讯都写在一个类里,外部调用只考虑传入参数即可,做到解耦效果
Unity的通讯是用协程方式实现网络通讯,怎么处理通讯返回的值后续的操作
代码实现
微卡智享
01
整理代码脚本
02
HttpRestful封装
HttpRestful完整代码
using System;using System.Collections;using System.Collections.Generic;using System.Text;using UnityEngine;using UnityEngine.Networking;public class HttpRestful : MonoBehaviour{private static HttpRestful _instance;public static HttpRestful Instance{get{if(_instance == null){GameObject goRestful = new GameObject("HttpRestful");_instance = goRestful.AddComponent<HttpRestful>();}return _instance;}}/// <summary>/// Get请求/// </summary>/// <param name="url"></param>/// <param name="actionResult"></param>public void Get(string url, Action<bool, string> actionResult = null){StartCoroutine(_Get(url, actionResult));}private IEnumerator _Get(string url, Action<bool, string> action){using (UnityWebRequest request = UnityWebRequest.Get(url)){yield return request.SendWebRequest();string resstr = "";if (request.isNetworkError || request.isHttpError){resstr = request.error;}else{resstr = request.downloadHandler.text;}if (action != null){action(request.isHttpError, resstr);}}}public void Post(string url, string data, Action<bool, string> actionResult = null){StartCoroutine(_Post(url, data, actionResult));}private IEnumerator _Post(string url, string data, Action<bool, string> action){using (UnityWebRequest request = new UnityWebRequest(url, "POST")){request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));request.SetRequestHeader("content-type", "application/json;charset=utf-8");request.downloadHandler = new DownloadHandlerBuffer();yield return request.SendWebRequest();string resstr = "";if (request.isNetworkError || request.isHttpError){resstr = request.error;}else{resstr = request.downloadHandler.text;}if (action != null){action(request.isHttpError, resstr);}}}}
03
调用HttpRestful
HttpRestful.Instance.Get(url, actionRes);HttpRestful.Instance.Post(url, json, actionRes);
UIScipts完整代码
using System;using System.Collections;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using UnityEngine;using UnityEngine.Networking;using UnityEngine.UI;public class UIScripts : MonoBehaviour{[Header("按钮")]public Button btnget;public Button btngetparm;public Button btnjson;public Button btnpost;[Space][Header("显示")]public Text txtshow;[Space][Header("输入框")]public InputField edturl;public InputField edtparm;//定义一个返回数据的Actionprivate Action<bool, string> actionRes;// Start is called before the first frame updatevoid Start(){InitAction();//Get按钮操作btnget.onClick.AddListener(() =>{Debug.Log(edturl.text);string url = edturl.text;HttpRestful.Instance.Get(url, actionRes);});btngetparm.onClick.AddListener(() =>{string url = edturl.text;string param = edtparm.text;string allurl = url + "/Info?Summary=" + param;HttpRestful.Instance.Get(allurl, actionRes);});btnjson.onClick.AddListener(() => StartCoroutine(JsonConvert()));btnpost.onClick.AddListener(() =>{WeatherForecast item = new WeatherForecast();item.Summary = "Alvin";item.Date = DateTime.Now;item.TemperatureC = 10;item.TemperatureF = 20;string json = JsonUtility.ToJson(item);string url = edturl.text + "/Reg";Debug.Log(url);HttpRestful.Instance.Post(url, json, actionRes);});}/// <summary>/// 写返回Action的处理方法/// </summary>private void InitAction(){actionRes = new Action<bool, string>((bl, str) =>{if (bl){txtshow.text = str;}else{string resjson = "{\"array\":" + str + "}";txtshow.text = resjson;WeatherData lists = JsonUtility.FromJson<WeatherData>(resjson);StringBuilder sb = new StringBuilder();foreach (WeatherForecast item in lists.array){sb.Append("Date:" + item.Date + " Summary:" + item.Summary + " TemperatureF:"+ item.TemperatureF + "TemperatureC:" + item.TemperatureC + "\r\n");}txtshow.text = sb.ToString();}});}IEnumerator JsonConvert(){WeatherForecast item = new WeatherForecast();item.Summary = "Alvin";item.Date = DateTime.Now;item.TemperatureC = 10;item.TemperatureF = 20;string json = JsonUtility.ToJson(item);txtshow.text = json;yield return new WaitForSeconds(3f);WeatherForecast newitem = JsonUtility.FromJson<WeatherForecast>(json);string showtext = "Summary:" + newitem.Summary + " Date:" + newitem.Date +" C:" + newitem.TemperatureC + " F:" + newitem.TemperatureF;txtshow.text = showtext;}}
实现效果
完
扫描二维码
获取更多精彩
微卡智享
「 往期文章 」
Unity3D网络通讯(二)--UnityWebRequest及JsonUtility请求Http Restful
本文分享自微信公众号 - 微卡智享(VaccaeShare)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。









