您好,登錄后才能下訂單哦!
小編給大家分享一下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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。