先上接口
using System;
using System.Collections.Generic;
using UnityEngine;
namespace YDB.Http
{
public interface IHttp
{
///
/// Get
///
/// 回调
/// 地址
void Get(Action callback,string url);
///
/// Get
///
/// 回调
/// 地址
void Get(Action callback, string url);
///
/// Get
///
/// 回调
/// 地址
void Get(Action callback, string url);
///
/// Post
///
/// 参数
/// 地址
void Post(Dictionary parameters, string url);
}
}
接口具体实现
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace YDB.Http
{
public class Http : MonoBehaviour,IHttp
{
public void Get(Action callback, string url)
{
if(callback == null)
{
Debug.LogWarning("回调为空,请求了也没屁用");
}
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
StartCoroutine(StartGet(callback,unityWebRequest));
}
public void Get(Action callback, string url)
{
if (callback == null)
{
Debug.LogWarning("回调为空,请求了也没屁用");
}
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
StartCoroutine(StartGet(callback, unityWebRequest));
}
public void Get(Action callback, string url)
{
if (callback == null)
{
Debug.LogWarning("回调为空,请求了也没屁用");
}
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
DownloadHandlerTexture downloadHandler = new DownloadHandlerTexture();
unityWebRequest.downloadHandler = downloadHandler;
StartCoroutine(StartGet(callback, unityWebRequest));
}
public void Post(Dictionary parameters, string url)
{
UnityWebRequest unityWebRequest = UnityWebRequest.Post(url, parameters);
StartCoroutine(StartPost(unityWebRequest));
}
private IEnumerator StartPost(UnityWebRequest uwr)
{
yield return uwr.SendWebRequest();
if (uwr.isHttpError || uwr.isNetworkError)
{
Debug.LogError(uwr.error);
}
else
{
Debug.Log("Post请求成功");
}
}
///
/// 异步网络请求
///
/// 回调类型
/// 回调
/// 请求参数
///
private IEnumerator StartGet(Action callback, UnityWebRequest uwr) where T : class
{
yield return uwr.SendWebRequest();
if (uwr.isHttpError || uwr.isNetworkError)
{
Debug.LogError(uwr.error);
}
else
{
Debug.Log("Get请求成功");
Type type = typeof(T);
if (type == typeof(string))
{
string text = uwr.downloadHandler.text;
callback(text as T);
}
else if (type == typeof(byte[]))
{
byte[] packet = uwr.downloadHandler.data;
callback(packet as T);
}
else if (type == typeof(Texture))
{
//特殊的文件类型,通过不同的Handler来下载
DownloadHandlerTexture downloadHandler = uwr.downloadHandler as DownloadHandlerTexture;
Texture texture = downloadHandler.texture;
callback(texture as T);
}
}
}
}
}



