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方法

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(, );
t2d.LoadImage(webRequest.downloadHandler.data); rawImage.texture = t2d;
}

调用Get方法只获取图片

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;
}

post方法

        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);
    void OnPostAction(UnityWebRequest webRequest)
{
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.Log("WebRequest error:" + webRequest.error);
return;
} //下载文本
Debug.Log(webRequest.downloadHandler.text);
}

//---------------------------------2018-1026------------------------------------------//更新

在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!");
}

unityWebRequest  LLAPI

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 == )
{
Debug.Log(www.downloadHandler.text);
}
}
}
}

unityweb Request请求的更多相关文章

  1. springMVC中 request请求数据绑定到Controller入参 过程剖析

    前言:Controller方法的参数类型可以是基本类型,也可以是封装后的普通Java类型.若这个普通Java类型没有声明任何注解,则意味着它的每一个属性都需要到Request中去查找对应的请求参数.众 ...

  2. iOS开发之Socket通信实战--Request请求数据包编码模块

    实际上在iOS很多应用开发中,大部分用的网络通信都是http/https协议,除非有特殊的需求会用到Socket网络协议进行网络数 据传输,这时候在iOS客户端就需要很好的第三方CocoaAsyncS ...

  3. Java中request请求之 - 带文件上传的form表单

    常用系统开发中总免不了显示图片,保存一些文件资料等操作. 这些操作的背后,就是程序员最熟悉的 enctype="multipart/form-data"类型的表单. 说起file类 ...

  4. Servlet的学习之Request请求对象(3)

    本篇接上一篇,将Servlet中的HttpServletRequest对象获取RequestDispatcher对象后能进行的[转发]forward功能和[包含]include功能介绍完. 首先来看R ...

  5. Servlet的学习之Request请求对象(2)

    在上一篇<Servlet的学习(十)>中介绍了HttpServletRequest请求对象的一些常用方法,而从这篇起开始介绍和学习HttpServletRequest的常用功能. 使用Ht ...

  6. 关于微信小程序的Request请求错误处理

    在学微信小程序的request请求的时候,一开始报“不在以下合法域名列表中,请参考文”的错误,后来又莫名其妙的报“400 Bad Request”错误,经过半天的研究,终于搞定了,把遇到的错误给大家分 ...

  7. javaWeb中request请求转发和response重定向

    1.访问资源 运用forward方法只能重定向到同一个Web应用程序中的一个资源. 而sendRedirect方法可以让你重定向到任何URL.  2.request.get Forward代码中的&q ...

  8. 【安卓网络请求开源框架Volley源码解析系列】定制自己的Request请求及Volley框架源码剖析

    通过前面的学习我们已经掌握了Volley的基本用法,没看过的建议大家先去阅读我的博文[安卓网络请求开源框架Volley源码解析系列]初识Volley及其基本用法.如StringRequest用来请求一 ...

  9. PHP Request请求封装

    /** * Request请求封装 * Class Request * @package tool */ class Request { // curl 请求错误码 protected static ...

随机推荐

  1. 【求赐教】VMware workstation 转VSphere

    首先我从其他电脑拷贝过来一台虚拟机(这个说法不知道准不准确,就是把所有文件夹都拷贝过来了),然后打开VMware,通过"打开虚拟机"这个操作,直接找到本地的.vmx文件,如下图所示 ...

  2. 使用 .gitignore 忽略 Git 仓库中的文件

    .gitignore 在Git中,很多时候你只想将代码提交到仓库,而不是将当前文件目录下的文件全部提交到Git仓库中,例如在MacOS系统下面的.DS_Store文件,或者是Xocde的操作记录,又或 ...

  3. SUSE Ceph 增加节点、减少节点、 删除OSD磁盘等操作 - Storage6

    一.测试环境描述 之前我们已快速部署好一套Ceph集群(3节点),现要测试在现有集群中在线方式增加节点 如下表中可以看到增加节点node004具体配置 主机名 Public网络 管理网络 集群网络 说 ...

  4. 【Python】机器学习之单变量线性回归练习(计算Cost Function)

    注:练习来自于吴恩达机器学习 翻译后的题目: 你是一个餐厅的老板,你想在其他城市开分店,所以你得到了一些数据(数据在本文最下方),数据中包括不同的城市人口数和该城市带来的利润.第一列是城市的人口数,第 ...

  5. 机器学习回顾篇(6):KNN算法

    1 引言 本文将从算法原理出发,展开介绍KNN算法,并结合机器学习中常用的Iris数据集通过代码实例演示KNN算法用法和实现. 2 算法原理 KNN(kNN,k-NearestNeighbor)算法, ...

  6. 什么是VR中的vection?

    Vection是VR领域的一个专有名词,其义指“在虚拟现实中给人带来‘移动’(self-motion)感觉的认知因素”1.也就是说,vection就是指那些给玩家带来“我正在这个虚拟环境中移动”这种感 ...

  7. Spring Boot 2.X(六):Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

  8. PID算法的理解及场景模拟

    增量式PID算法的简化版之后的公式: △u(t)=Ae(t)-Be(t-1)+Ce(t-2) △u:PID控制器输出的下一时刻的调整量 e(t):PID控制器在当前时刻的状态变化量-给定值 e(t-1 ...

  9. 我又不是你的谁--java instanceof操作符用法揭秘

    背景故事 <曾经最美>是朱铭捷演唱的一首歌曲,由陈佳明填词,叶良俊谱曲,是电视剧<水晶之恋>的主题曲.歌曲时长4分28秒. 歌曲歌词: 看不穿你的眼睛 藏有多少悲和喜 像冰雪细 ...

  10. Python 爬虫(四):Selenium 框架

    Selenium 是一个用于测试 Web 应用程序的框架,该框架测试直接在浏览器中运行,就像真实用户操作一样.它支持多种平台:Windows.Linux.Mac,支持多种语言:Python.Perl. ...