Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encapsulate HttpRestful request in Unity3D Network Communication

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to encapsulate HttpRestful requests in Unity3D network communications. I hope you will get something after reading this article. Let's discuss it together.

Clean up the code script

We build a Model folder (for object classes) and a Utils folder (for utility classes) under Scripts, then move the WeatherForecase class to Model, create a Network folder under the Utils folder for handling network communications, and then create a HttpRestful C # script under this folder.

02

HttpRestful encapsulation

Define a static instance, and then write the corresponding instance method to get the method.

Write the co-program method call of Get, where the last parameter is the method of Action, where the first parameter bool of Action is used to return the success or failure of the communication, and the second parameter string is the returned communication information.

The parameters passed in the Get method of the external call are the same, and the internal operation is the direct account opening and cooperation operation. The following Post implementation is also written in this way, except that you need to add the data we passed in the passed parameters.

HttpRestful complete code 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 ();} return _ instance;}}

# region Get request / Get request / public void Get (string url, Action actionResult = null) {StartCoroutine (_ Get (url, actionResult));}

Private IEnumerator _ Get (string url, Action 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 request public void Post (string url, string data, Action actionResult = null) {StartCoroutine (_ Post (url, data, actionResult));}

Private IEnumerator _ Post (string url, string data, Action 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

Call HttpRestful

We copied a UIScripts again, and then added Old to one of the names, so we didn't have to reset it any more, we just modified it in the UIScripts script.

First define an Action where the parameters are the same as the Action method passed in the HttpRestful.

Then add an InitAction method, which writes its implementation method to the defined actionRes. In the method, it is determined that if the communication fails to display the text directly, it will be processed after success, and then the processed data will be displayed, because the data type returned after Get and Post calls is the same, so we have written an Action here that can call this method for later data processing.

Then we first call the initialization Action in Start, and then use the

HttpRestful.Instance.Get (url, actionRes); HttpRestful.Instance.Post (url, json, actionRes); the data can be processed directly, and the rest of the methods we called yesterday can be deleted.

UIScipts complete code 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 ("button")] public Button btnget; public Button btngetparm; public Button btnjson; public Button btnpost

[Space] [Header ("display")] public Text txtshow

[Space] [Header ("input box")] public InputField edturl; public InputField edtparm

/ / define an Action private Action actionRes; / / Start is called before the first frame update void Start () {InitAction () that returns data

/ / Get button operation 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);};}

/ write the processing method that returns Action / private void InitAction () {actionRes = new Action ((bl, str) = > {if (bl) {txtshow.text = str) } else {string resjson = "{\" array\ ":" + str + "}"; txtshow.text = resjson; WeatherData lists = JsonUtility.FromJson (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 (json); string showtext = "Summary:" + newitem.Summary + "Date:" + newitem.Date + "C:" + newitem.TemperatureC + "F:" + newitem.TemperatureF; txtshow.text = showtext;}}

Realize the effect

The above figure is the implementation effect of encapsulating and calling WebApi. Later, I compiled it under the Android platform, and there is no problem with the call. This way can be used across platforms. After reading this article, I believe you have a certain understanding of "how to encapsulate HttpRestful requests in Unity3D network communications". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report