学习目标:

using LitJson;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.Networking;public class WebRequestTest :MonoBehaviour
{public delegate void HttpHelperPostGetCallbacks(long code, HttpHelperRequests request, HttpHelperResponses rsponse);//Http请求信息[Serializable]public struct HttpHelperRequests{//请求地址public string url;//表单字段public JsonData filelds;//表头public JsonData headers;public string token;public string session;}//Http返回信息[Serializable]public struct HttpHelperResponses{//返回Http状态码public long code;//返回http提示信息public string message;//请求接口时返回的头字典public Dictionary<string, string> headers;//请求API接口时返回的文本内容public string text;//请求返回的字节数值public byte[] bytes;//下载完成时返回的Texturepublic Texture texture;//下载资源时用到的线程public Thread thread;//下载的ABpublic AssetBundle bundle;/// <summary>/// 将text反序列化成T类型/// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public T Deserialize<T>(){return JsonConvert.DeserializeObject<T>(this.text);}}#region UnityWebRequestprivate void SendRequest(string url, HttpHelperPostGetCallbacks callback, JsonData fields = null, JsonData header = null, int timeout = 5){StartCoroutine(_SendRequest(url, callback, fields, header, timeout));}IEnumerator _SendRequest(string url, HttpHelperPostGetCallbacks callback, JsonData fields = null, JsonData header = null, int timeout = 5){using (UnityWebRequest webRequest = new UnityWebRequest(url)){webRequest.timeout = timeout;yield return webRequest.SendWebRequest();//组装 请求信息HttpHelperRequests request = new HttpHelperRequests();request.url = url;request.filelds = fields;request.headers = header;//组装 返回信息HttpHelperResponses response = new HttpHelperResponses();response.code = webRequest.responseCode;response.message = webRequest.error;response.headers = webRequest.GetResponseHeaders();response.text = webRequest.downloadHandler.text;response.bytes = webRequest.downloadHandler.data;//调用 委托callback?.Invoke(webRequest.responseCode, request, response);//结束 处理占用资源//尽快停止UnityWebRequestwebRequest.Abort();//默认值是true,调用该方法不需要设置Dispose(),Unity就会自动在完成后调用Dispose()释放资源。webRequest.disposeDownloadHandlerOnDispose = true;//不再使用此UnityWebRequest,并应清理它正在使用的任何资源webRequest.Dispose();}}#endregion#region Post方法 /*Post方法将一个表上传到远程的服务器,一般来说我们登陆某个网站的时候会用到这个方法,我们的账号密码会以一个表单的形式传过去。*/#region POST普通表单请求,支持Header,Authorization/// <summary>/// POST普通表单请求/// POST普通表单参数请求 - 数据以Parameters形式发送/// </summary>/// <param name="url">目标URL</param>/// <param name="callback">请求完成回调</param>/// <param name="fields">表单字段</param>/// <param name="header">请求头字典, 默认Content-Type=application/json</param>/// <param name="timeout"></param>private void Post(string url, HttpHelperPostGetCallbacks callback, JsonData fields = null,JsonData header = null, int timeout = 5){StartCoroutine(_Post(url, callback, fields, header, timeout));}IEnumerator _Post(string url,HttpHelperPostGetCallbacks callback, JsonData fields = null,JsonData header = null,int timeout = 5){using (UnityWebRequest webRequest = UnityWebRequest.Post(url,fields!=null?fields.ToJson():null)){//设定超时webRequest.timeout = timeout;//设置请求头  根据实际需求来webRequest.SetRequestHeader("Authorization", "");//开始与远程服务器通信//等待通行完成yield return webRequest.SendWebRequest();//组装 请求信息HttpHelperRequests request = new HttpHelperRequests();request.url = url;request.filelds = fields;request.headers = header;//组装 返回信息HttpHelperResponses response = new HttpHelperResponses();response.code = webRequest.responseCode;response.message = webRequest.error;response.headers = webRequest.GetResponseHeaders();response.text = webRequest.downloadHandler.text;response.bytes = webRequest.downloadHandler.data;//调用 委托callback?.Invoke(webRequest.responseCode, request, response);//结束 处理占用资源//尽快停止UnityWebRequestwebRequest.Abort();//默认值是true,调用该方法不需要设置Dispose(),Unity就会自动在完成后调用Dispose()释放资源。webRequest.disposeDownloadHandlerOnDispose = true;//不再使用此UnityWebRequest,并应清理它正在使用的任何资源webRequest.Dispose();}}#endregion#region POST RawBody请求,支持Header,Authorization/// <summary>/// 进行POST请求,数据以Raw格式携带在Body中进行请求/// </summary>/// <param name="url">目标URL地址</param>/// <param name="callback">回调完成函数</param>/// <param name="fields">携带数据</param>/// <param name="header"></param>/// <param name="timeout"></param>private void PostRaw(string url, HttpHelperPostGetCallbacks callback, JsonData fields = null, JsonData header = null, int timeout = 5){StartCoroutine(_PostRaw(url, callback, fields, header, timeout));}IEnumerator _PostRaw(string url,HttpHelperPostGetCallbacks callback, JsonData fields,JsonData header,int timeout = 5){using (UnityWebRequest webRequest = UnityWebRequest.Post(url,"POST")){//负责拒绝或接受在https请求中收到的证书,用于Https请求中的证书处理webRequest.certificateHandler = new CustomCertHandler();//设定超时webRequest.timeout = timeout;//设置信息头  根据实际需求来webRequest.SetRequestHeader("Content-Type", "application/json;");//处理请求头设置if (header != null){foreach (var item in header.Keys){webRequest.SetRequestHeader(item, header[item].ToString());}}//设置携带数据if (fields != null){webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(fields.ToJson()));}yield return webRequest.SendWebRequest();//组装 请求信息HttpHelperRequests request = new HttpHelperRequests();request.url = url;request.filelds = fields;request.headers = header;//组装 返回信息HttpHelperResponses response = new HttpHelperResponses();response.code = webRequest.responseCode;response.message = webRequest.error;response.headers = webRequest.GetResponseHeaders();response.text = webRequest.downloadHandler.text;response.bytes = webRequest.downloadHandler.data;//调用 委托callback?.Invoke(webRequest.responseCode, request, response);//结束 处理占用资源//尽快停止UnityWebRequestwebRequest.Abort();//默认值是true,调用该方法不需要设置Dispose(),Unity就会自动在完成后调用Dispose()释放资源。webRequest.disposeDownloadHandlerOnDispose = true;//不再使用此UnityWebRequest,并应清理它正在使用的任何资源webRequest.Dispose();}}#endregion#endregion#region GET方法 #region GET普通表单请求,支持Header,Authorization/// <summary>/// 普通GET请求/// </summary>/// <param name="url">Get请求目标URL</param>/// <param name="callback">请求完成回调函数</param>/// <param name="fields">标单字段数据,Dictionary类型 </param>/// <param name="header">请求Header数据,Dictionary类型 </param>/// <param name="timeout">超时时间  默认5秒</param>public void Get(string url, HttpHelperPostGetCallbacks callback, JsonData fields = null, JsonData header = null, int timeout = 5){StartCoroutine(_Get(url, callback, fields, header, timeout));}private IEnumerator _Get(string url, HttpHelperPostGetCallbacks callback, JsonData fields = null, JsonData header = null, int timeout = 5){string targetUrl = url;StringBuilder sb = new StringBuilder();if (fields != null){foreach (var Key in fields.Keys){sb.Append(Key + "=" + fields[Key] + "&");}if (url.Contains("?")){targetUrl = url + "&" + sb.ToString();}else{targetUrl = url + "?" + sb.ToString();}targetUrl = targetUrl[targetUrl.Length - 1] == '&' ? targetUrl.Substring(0, targetUrl.Length - 1) : targetUrl;}using (UnityWebRequest webRequest =  UnityWebRequest.Get(targetUrl)){//设定超时webRequest.timeout = timeout;//处理请求头设置webRequest.SetRequestHeader("Authorization", "");if (header != null){foreach (var item in header.Keys){webRequest.SetRequestHeader(item.ToString(), header[item].ToString());}}yield return webRequest.SendWebRequest();//组装 请求信息HttpHelperRequests request = new HttpHelperRequests();request.url = url;request.filelds = fields;request.headers = header;//组装 返回信息HttpHelperResponses response = new HttpHelperResponses();response.code = webRequest.responseCode;response.message = webRequest.error;response.headers = webRequest.GetResponseHeaders();response.text = webRequest.downloadHandler.text;response.bytes = webRequest.downloadHandler.data;//调用 委托callback?.Invoke(webRequest.responseCode, request, response);//结束 处理占用资源//尽快停止UnityWebRequestwebRequest.Abort();//默认值是true,调用该方法不需要设置Dispose(),Unity就会自动在完成后调用Dispose()释放资源。webRequest.disposeDownloadHandlerOnDispose = true;//不再使用此UnityWebRequest,并应清理它正在使用的任何资源webRequest.Dispose();}}#endregion#endregion}

学习内容:

提示:这里可以添加要学的内容
例如:
1、 搭建 Java 开发环境
2、 掌握 Java 基本语法
3、 掌握条件语句
4、 掌握循环语句


学习时间:

提示:这里可以添加计划学习的时间
例如:
1、 周一至周五晚上 7 点—晚上9点
2、 周六上午 9 点-上午 11 点
3、 周日下午 3 点-下午 6 点


学习产出:

提示:这里统计学习计划的总量
例如:
1、 技术笔记 2 遍
2、CSDN 技术博客 3 篇
3、 学习的 vlog 视频 1 个

Unity UnityWebRequest Get与Post应用相关推荐

  1. Unity UnityWebRequest 下载封装

    Unity UnityWebRequest 下载封装 对unity原生的UnityWebRequest 进行二次封装 public void UnityWebRequestLoad<T>( ...

  2. Unity UnityWebRequest下载文件 替代WWW

    今天测试那边提了个问题,就是当网络极差的时候,游戏下载将会停止(即一直在等待yield return www)当时间较长时网络恢复将无法继续下载,也没有提示,需要重启才能重新下载.因为WWW不存在设置 ...

  3. Unity UnityWebRequest: InvalidOperationException: Insecure connection not allowed

    该错误是由于新版本的unity默认是不允许HTTP请求的,可在以下路径修改 将其修改即可访问 选择Always allowed,会弹出一个警告: Plain text HTTP connections ...

  4. Unity UnityWebRequest一些基本用法

    using System; using System.Collections; using System.IO; using UnityEditor; using UnityEngine; using ...

  5. Unity使用UnityWebRequest实现本地日志上传到web服务器

    一.前言 Unity项目开发中,遇到bug的时候,我们一般是通过日志来定位问题,所以写日志到本地文件,或者把日志文件上传到web服务器这样的功能就很必要了.下面就介绍下如何实现日志写入本地文件和上传本 ...

  6. Unity 最新UnityWebRequest下载,同时显示下载进度,和 显示网速,今天贴出来和大家分享

    Unity 最新UnityWebRequest下载网络资源,支持断点续传.多文件同时下载,同时显示下载进度,和 显示网速,今天贴出来和大家分享 显示网速图片 附上案例链接 可下载 https://do ...

  7. Unity用UnityWebRequest和 BestHttp的GET和POST表单提交,与php交互

    目录 在unity2021中,WWW的资源加载方式过时了,新的方法为UnityWebRequest BestHttp的Get方式和Post方式 部分API 在unity2021中,WWW的资源加载方式 ...

  8. Unity 工具类 之 WWW/UnityWebRequest 下载压缩文件(zip),解压到本地且加载使用解压数据的简单案例(内也含压缩文件例子)

    Unity 工具类 之 WWW/UnityWebRequest 网络下载压缩文件(zip),解压到本地,且加载使用解压数据的简单案例(内也含压缩文件例子) 目录 Unity 工具类 之 WWW/Uni ...

  9. Unity 启动时带参数,网页后端进行数据交互 UnityWebRequest ,Post,Get,Delete

    打包后启动.exe带参数 启动传参数可以参考这篇文章: 浏览器调用本地exe(应用程序)方法 Unity准备工作 需要用到这个API Environment.GetCommandLineArgs() ...

最新文章

  1. Laravel安装后没有vendor文件夹
  2. 如何实现iframe(嵌入式帧)的自适应高度
  3. review what i studied `date` - 2017-4-12
  4. Tensorflow中2D卷积API使用
  5. C# 将程序添加开机启动的三种方式
  6. 子元素浮动,父元素高度为0现象解释和原理浅见
  7. hdu 1861 游船出租 tag:模拟
  8. 女人水润有诀窍,菜谱保你水灵灵 - 生活至上,美容至尚!
  9. 简单shellcode编写
  10. redis 任务队列
  11. 《今日简史》一、旧故事已然崩坏,新故事尚未构建
  12. 数据采集:Flume和Logstash的工作原理和应用场景
  13. Java练习题:算法(冒泡排序)
  14. Lwip 奔溃掉线内存申请不出来也许大部分是竞争问题!
  15. Mac电脑使用:下载安装SourceTree的步骤以及使用方法
  16. pytorch每日一学22(torch.empty()、torch.empty_like()、torch.empty_strided())创建未初始化数据的tensor
  17. 优宝库强势入围深圳创新创业大赛半决赛,珠宝行业仅此一家
  18. Linux中系统进程的详细管理
  19. 【连载】IOS开发-图形渲染(一)
  20. cannot find a java se sdk installed at path_SDK管理器找不到Java

热门文章

  1. 运维进阶——firewall详解
  2. AltiumDesigner灵活利用X、Y镜像功能
  3. 苹果隐私十年史:变与不变(1)突变与营销
  4. Sofia-SIP辅助文档十六 - Sofia SIP用户代理库 - msg - 消息解析模块
  5. 五分钟理解服务器 SMP、NUMA、MPP 三大体系结构
  6. CSS list-style-type 属性
  7. [交流]我是怎样看大片学英语的(你可能知道,给不知到的人写的)
  8. #443 特辑:当有九条命的好日子不复存在 (feat. 安全出口FM)
  9. 《影响中国大数据产业进程100人》张华平:如何应用网络搜索挖掘内容价值
  10. csdn 涨粉攻略 代码(二)粉丝数 webmagic 爬虫