小编给大家分享一下Unity3D网络通讯中HttpRestful请求如何封装,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
整理代码脚本
02
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;
}
}
#region Get请求
/// <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);
}
}
}
#endregion
#region POST请求
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);
}
}
}
#endregion
}
03
调用HttpRestful
HttpRestful.Instance.Get(url, actionRes);HttpRestful.Instance.Post(url, json, actionRes);
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;
//定义一个返回数据的Action
private Action<bool, string> actionRes;
// Start is called before the first frame update
void 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网络通讯中HttpRestful请求如何封装”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。