UnityWebRequest是新的网络请求Api,分为LLApi和HLApi,其中LLApi为低级api,所谓低级api是指只是提供最基本的api接口,然后需要通过不同的参数来确定请求方式。为此unity提供了高级api(HLApi)即对不同的功能进行了封装,以下基于HLApi做了简单封装。
using System.Collections;
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections.Generic;
using System.IO;
public class WebRequestUtility : MonoBehaviour
{
public static WebRequestUtility Instance;
enum RequestType
{
TEXT_GET,
TEXTUREE_GET,
ASSETBUNDEL,
POST
}
public void Get(string url,Action<UnityWebRequest> action)
{
StartCoroutine(Request(url,action,RequestType.TEXT_GET));
}
public void GetTexture(string url,Action<UnityWebRequest> action)
{
StartCoroutine(Request(url, action, RequestType.TEXTUREE_GET));
}
public void GetAssetBundle(string url,Action<UnityWebRequest> action)
{
StartCoroutine(Request(url, action, RequestType.ASSETBUNDEL));
}
public void Post(string url, Action<UnityWebRequest> action, List<IMultipartFormSection> formData)
{
StartCoroutine(Request(url, action, RequestType.POST, formData));
}
IEnumerator Request(string url,Action<UnityWebRequest> action,RequestType type, List<IMultipartFormSection> formData=null)
{
UnityWebRequest webRequest = null;
switch (type)
{
case RequestType.TEXT_GET:
webRequest = UnityWebRequest.Get(url);
break;
case RequestType.TEXTUREE_GET:
webRequest = UnityWebRequestTexture.GetTexture(url);
break;
case RequestType.ASSETBUNDEL:
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);
break;
case RequestType.POST:
webRequest = UnityWebRequest.Post(url, formData);
break;
default:
break;
}
if(webRequest==null)
{
Debug.Log("WebRequest initialise error");
yield break;
}
yield return webRequest.SendWebRequest();
action?.Invoke(webRequest);
webRequest.Dispose();
webRequest = null;
Resources.UnloadUnusedAssets();
}
private void Awake()
{
Instance = this;
}
}
调用方法Get(texUrlGet, OnGetAction);
//OnGetAction回调
void OnGetAction(UnityWebRequest webRequest)
{
if(webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.Log("WebRequest error:"+webRequest.error);
return;
}
//下载文本
Debug.Log(webRequest.downloadHandler.text);
//下载图片
Texture2D t2d = new Texture2D(10, 10);
t2d.LoadImage(webRequest.downloadHandler.data);
rawImage.texture = t2d;
}
GetTexture(texUrlGet, OnGetTextueAction);
void OnGetTextueAction(UnityWebRequest webRequest)
{
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.Log("WebRequest error:" + webRequest.error);
return;
}
DownloadHandlerTexture texHandler = (DownloadHandlerTexture)webRequest.downloadHandler;
rawImage.texture = ((DownloadHandlerTexture)webRequest.downloadHandler).texture;
}
调用方法:
string headPath = @"D:\zzh.png";
byte[] bytes = File.ReadAllBytes(headPath);
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("api_key", "**********************"));
formData.Add(new MultipartFormDataSection("api_secret", "***************************"));
//formData.Add(new MultipartFormDataSection("image_url", texUrlGet));
formData.Add(new MultipartFormFileSection("image_file", bytes, "zzh.png", "application/octet-stream"));
Post("https://api-cn.faceplusplus.com/facepp/v3/detect", OnPostAction, formData);
formData仍旧可以使用WWWForm类进行post数据添加
回调函数:
void OnPostAction(UnityWebRequest webRequest)
{
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.Log("WebRequest error:" + webRequest.error);
return;
}
//下载文本
Debug.Log(webRequest.downloadHandler.text);
在post请求时根据需求分为四种模式,详细见https://www.cnblogs.com/llstart-new0201/p/6825058.html;所以此次更新增加了post模式,但新加的并未进行测试
using System.Collections;
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections.Generic;
using System.IO;
public class WebRequestUtility : MonoBehaviour
{
public RawImage rawImage;
public static WebRequestUtility Instance;
enum RequestType
{
TEXT_GET,
TEXTUREE_GET,
ASSETBUNDEL,
POST_FORM,
POST_URLENCODED,
POST_JSON,
POST_XML
}
class PostContent
{
public WWWForm formData;
public string stringContent;
public PostContent(WWWForm formData)
{
this.formData = formData;
}
public PostContent(string text)
{
this.stringContent = text;
}
}
public void Get(string url,Action<UnityWebRequest> action)
{
StartCoroutine(Request(url,action,RequestType.TEXT_GET));
}
public void GetTexture(string url,Action<UnityWebRequest> action)
{
StartCoroutine(Request(url, action, RequestType.TEXTUREE_GET));
}
public void GetAssetBundle(string url,Action<UnityWebRequest> action)
{
StartCoroutine(Request(url, action, RequestType.ASSETBUNDEL));
}
public void Post(string url, Action<UnityWebRequest> action, WWWForm formData)
{
StartCoroutine(Request(url, action, RequestType.POST_FORM, new PostContent(formData)));
}
public void PostUrlEncoded(string url,Action<UnityWebRequest> action,string json)
{
StartCoroutine(Request(url, action, RequestType.POST_URLENCODED,new PostContent(json)));
}
public void PostJson(string url, Action<UnityWebRequest> action, string json)
{
StartCoroutine(Request(url, action, RequestType.POST_JSON, new PostContent(json)));
}
public void PostXml(string url, Action<UnityWebRequest> action, string json)
{
StartCoroutine(Request(url, action, RequestType.POST_XML, new PostContent(json)));
}
IEnumerator Request(string url,Action<UnityWebRequest> action,RequestType type, PostContent postContent =null)
{
UnityWebRequest webRequest = null;
switch (type)
{
case RequestType.TEXT_GET:
webRequest = UnityWebRequest.Get(url);
break;
case RequestType.TEXTUREE_GET:
webRequest = UnityWebRequestTexture.GetTexture(url);
break;
case RequestType.ASSETBUNDEL:
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);
break;
case RequestType.POST_FORM:
webRequest = UnityWebRequest.Post(url, postContent.formData);
break;
case RequestType.POST_URLENCODED:
webRequest = UnityWebRequest.Post(url, postContent.stringContent);
//可以不进行设置,此时默认为urlencoded
webRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
break;
case RequestType.POST_JSON:
webRequest = UnityWebRequest.Post(url, postContent.stringContent);
webRequest.SetRequestHeader("Content-Type", "application/json");
break;
case RequestType.POST_XML:
webRequest = UnityWebRequest.Post(url, postContent.stringContent);
webRequest.SetRequestHeader("Content-Type", "text/xml");//注:text/plain为纯文本
break;
default:
break;
}
if(webRequest==null)
{
Debug.Log("WebRequest initialise error");
yield break;
}
yield return webRequest.SendWebRequest();
action?.Invoke(webRequest);
action = null;
webRequest.Dispose();
webRequest = null;
Resources.UnloadUnusedAssets();
}
private void Awake()
{
Instance = this;
}
}
鉴于post请求可能存在的问题,如https://www.jianshu.com/p/0f1f24829db3所述,做如下代码,
//通过PUT方式构造HTTP请求
byte[] myData = System.Text.Encoding.UTF8.GetBytes("This is some test data");
UnityWebRequest www = UnityWebRequest.Put("http://www.my-server.com/upload", myData);
//构造好后,手动将请求方式更改为POST
www.method = UnityWebRequest.kHttpVerbPOST;
//常规的发送,接收操作
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
Debug.Log("Upload complete!");
}
public IEnumerator PostUrl(string url, string postData)
{
using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
{
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
if (www.responseCode == 200)
{
Debug.Log(www.downloadHandler.text);
}
}
}
}