本篇来实现Http通信
Http比较简单直接使用UnityWebRequest进行封装即可
虽然Unity有UnityWebRequest且非常的完整
但是在使用上比较麻烦
所以我们会对它进行封装,这里我创建了一个HttpReq类,继承了Mono单例
public class HttpReq : MonoSingleton<HttpReq>
{
}
Http请求有很多类型:
而我们最常用的就是get和post,现在我们就来实现它
//Get请求
IEnumerator GetReq(string url, Action<string> callback)
{
UnityWebRequest webRequest = UnityWebRequest.Get(url);
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ProtocolError ||
webRequest.result == UnityWebRequest.Result.ConnectionError)
Debug.Log(webRequest.error);
else
{
callback?.Invoke(webRequest.downloadHandler.text);
}
}
//Post请求
IEnumerator PostReq(string url, string data, Action<string> callback)
{
UnityWebRequest webRequest = UnityWebRequest.Post(url, data);
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ProtocolError ||
webRequest.result == UnityWebRequest.Result.ConnectionError)
Debug.Log(webRequest.error);
else
{
callback?.Invoke(webRequest.downloadHandler.text);
}
}
这里我们定义了两个携程来发送Http请求,但是并没有开启,接下来是开启请求
public void Get(string url, Action<string> callback)
{
StartCoroutine(GetReq(url, callback));
}
public void Post(string url, string data, Action<string> callback)
{
StartCoroutine(PostReq(url, data, callback));
}
这样我们就可以通过
HttpReq.Instance.Get(url, callback);
HttpReq.Instance.Post(url, data, callback);
来请求Http了,将他们添加到API类中
public static void HttpReqGet(string url, Action<string> callback)
{
HttpReq.Instance.Get(url, callback);
}
public static void HttpReqPost(string url, string data, Action<string> callback)
{
HttpReq.Instance.Post(url, data, callback);
}
并生成胶水代码后,我们就可以在TS直接调用他们了
API.HttpReqGet(url, callback);
//callback使用this.GetResp.bind(this)防止丢失this对象
API.HttpReqPost(url, data, this.PostResp.bind(this));
//callback使用this.PostResp.bind(this)防止丢失this对象