您好,登錄后才能下訂單哦!
小編給大家分享一下Unity3D網(wǎng)絡(luò)通訊中HttpRestful請(qǐng)求如何封裝,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
整理代碼腳本
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請(qǐng)求
/// <summary>
/// Get請(qǐng)求
/// </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請(qǐng)求
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
調(diào)用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;
//定義一個(gè)返回?cái)?shù)據(jù)的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;
}
}
實(shí)現(xiàn)效果
看完了這篇文章,相信你對(duì)“Unity3D網(wǎng)絡(luò)通訊中HttpRestful請(qǐng)求如何封裝”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。