目录

在unity2021中,WWW的资源加载方式过时了,新的方法为UnityWebRequest

BestHttp的Get方式和Post方式

部分API


在unity2021中,WWW的资源加载方式过时了,新的方法为UnityWebRequest

实际开发过程中,游戏APP通常在连接游戏服务器之前先从web服务器获取GM配置的相关信息,这里模拟服务器和前端的简单交互,用Unity的UnityWebRequest的GET和POST两种方式提交表单,向后端请求数据,后端返回JSON数据,前端根据返回数据执行相关逻辑。

Demo的内容:

  1. 用UnityWebRequest的GET和POST表单提交,与php(返回JSON)交互
  2. 从web服务器下载图片替换本地显示的图片
  3. 用BestHttp插件的GET和POST表单提交,与php(返回JSON)交互

 演示图片:

 演示视频:

UnityWebRequest下载图片demo

直接上代码,都是老司机,demo仅供参考玩

PHP脚本:GetInfo.php

<?php// 如果是GET请求
if ($_SERVER['REQUEST_METHOD'] == 'GET') {// Get访问。。。。if ($_GET["action"]=="login"){if ($_GET['user'] == 'admin' && $_GET['pwd'] == 'admin' && $_GET['time']>202205312146151616){exit(json_encode(['code' => '200','msg' => 'GET_success','num' => 71, 'data' => ['aa' => true, 'bb' => false, 'cc' => 15, 'dd' => 3.1415, 'ee' => [1,2,3], ]]));// var_dump("登录成功");}  else {exit(json_encode(['code' => '200','msg' => 'user does not exist','data' => []]));}} else if ($_GET["action"]=="get_picture_num"){exit(json_encode(['code' => '200','msg' => 'GET_success','num' => 71, ]));}else{exit(json_encode(['code' => '200','msg' => 'GET 请求','data' => []])); }}// 如果是POST请求
if ($_SERVER['REQUEST_METHOD'] == 'POST') {// POST访问。。。。if ($_POST["action"]=="login"){if ($_POST['user'] == 'admin' && $_POST['pwd'] == 'admin' && $_POST['time']>202205312146151616){exit(json_encode(['code' => '200','msg' => 'POST_success','num' => 71, 'data' => ['aa' => true, 'bb' => false, 'cc' => 15, 'dd' => 3.1415, 'ee' => [1,2,3], ]]));// var_dump("登录成功");} else {exit(json_encode(['code' => '200','msg' => 'user does not exist','data' => []]));}}  else {exit(json_encode(['code' => '200','msg' => 'POST 请求','data' => []])); }}

C#代码:DownloadUI.cs

using MiniJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;public class DownloadUI : MonoBehaviour
{//图片占位图public Texture placeholder;//要替换背景的RawImagepublic RawImage testholder;//点击左边这个按钮,显示默认占位图public Button setDefaultImage;//点击这个按钮,从Web服务器加载图片显示在上面的RawImagepublic Button setWebImage;//索引,默认从第一张图片开始下载private int index;// 要下载的图片的总数量private int num;void Start(){//测试,用POST向服务器提交信息StartCoroutine(HttpPostRequest());//测试,用GET向服务器提交信息StartCoroutine(HttpGetRequest());//从服务器获取要下载的图片的数量StartCoroutine(HttpGetPictureNumRequest());//两个按钮的点击事件(注:此处省略了用代码获取UI主件,直接在UI上拖拽设置了)setDefaultImage.onClick.AddListener(DefaultCallBack);setWebImage.onClick.AddListener(WebCallBack);//初始化索引,默认从第一张图片开始下载index = 1;}/// <summary>/// 从服务器获取要下载的图片的数量/// </summary>/// <returns></returns>private IEnumerator HttpGetPictureNumRequest(){string url = "http://wy.bestshe.top/game/GetInfo.php?action=get_picture_num";UnityWebRequest web = UnityWebRequest.Get(url);yield return web.SendWebRequest();if (web.isDone){string str = Encoding.UTF8.GetString(web.downloadHandler.data);Dictionary<string, object> data = (Dictionary<string, object>)Json.Deserialize(str);if (data.ContainsKey("num")){num = Convert.ToInt32(data["num"]);}}}private void WebCallBack(){string url = "http://wy.bestshe.top/game/";if (index > num) index = 1;url = url + index + ".jpeg";AsyncImageDownload.Instance.SetAsyncImage(url, testholder);index++;}private void DefaultCallBack(){//开始下载图片前,如果没有图片,则将UITexture的主图片设置为占位图if (testholder.texture == null){testholder.texture = placeholder;}else{//再次点击default替换掉下载的图testholder.texture = placeholder;}}private IEnumerator HttpPostRequest(){string url = "http://wy.bestshe.top/game/GetInfo.php";WWWForm form = new WWWForm();form.AddField("action", "login");form.AddField("user", "admin");form.AddField("pwd", "admin");form.AddField("time", string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now));UnityWebRequest web = UnityWebRequest.Post(url, form);yield return web.SendWebRequest();if (web.result != UnityWebRequest.Result.Success)Debug.Log(" error:" + web.error);else if (web.isDone){string str = Encoding.UTF8.GetString(web.downloadHandler.data);Debug.Log("Post发送成功----" + str);}}private IEnumerator HttpGetRequest(){string url = "http://wy.bestshe.top/game/GetInfo.php?action=login&user=admin&pwd=admin";url = SetUrlTime(url);UnityWebRequest web = UnityWebRequest.Get(url);yield return web.SendWebRequest();if (web.result != UnityWebRequest.Result.Success)Debug.Log(" error:" + web.error);else if (web.isDone){string str = Encoding.UTF8.GetString(web.downloadHandler.data);Debug.Log("Get发送成功----" + str);}}public string SetUrlTime(string url){string symbol = url.IndexOf("?") > -1 ? "&" : "?";url = string.Format("{0}{1}time={2}", url, symbol, string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now));return url;}
}

 AsyncImageDownload.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.Networking;
using UnityEngine.UI;public class AsyncImageDownload : MonoBehaviour
{public static AsyncImageDownload Instance = null;private static string path;public Dictionary<string, Texture2D> textureCache = new Dictionary<string, Texture2D>();void Awake(){Instance = this;path = Application.persistentDataPath + "/ImageCache/";if (!Directory.Exists(path)){Directory.CreateDirectory(path);}}public void SetAsyncImage(string url, RawImage texture){//判断是否是第一次加载这张图片if (!File.Exists(path + url.GetHashCode())){//如果之前不存在缓存文件StartCoroutine(DownloadImage(url, texture));}else{StartCoroutine(LoadLocalImage(url, texture));}}IEnumerator DownloadImage(string url, RawImage texture){using UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url);yield return uwr.SendWebRequest();if (uwr.result != UnityWebRequest.Result.Success)Debug.Log("DownloadImage error:" + uwr.error);else if (uwr.isDone){//将下载到的图片赋值到RawImage上Texture2D mTexture2D = DownloadHandlerTexture.GetContent(uwr);texture.texture = mTexture2D;//将下载到的图片赋值到RawImage上(二选一都行)//texture.texture = ((DownloadHandlerTexture)uwr.downloadHandler).texture;//将图片保存至缓存路径byte[] jpgData = mTexture2D.EncodeToJPG();File.WriteAllBytes(path + url.GetHashCode(), jpgData);textureCache[url] = mTexture2D;}}IEnumerator LoadLocalImage(string url, RawImage texture){string filePath = "file:///" + path + url.GetHashCode();if (textureCache.TryGetValue(url, out Texture2D tex)){texture.texture = tex;}else{using UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(filePath);yield return uwr.SendWebRequest();if (uwr.result != UnityWebRequest.Result.Success)Debug.Log("DownloadImage error:" + uwr.error);else if (uwr.isDone){Texture2D mTexture2D = DownloadHandlerTexture.GetContent(uwr);textureCache[url] = mTexture2D;texture.texture = mTexture2D;}}}
}

BestHttp的Get方式和Post方式

/*----------------------------------------------------------------Created by 王银文件名: BestHttpTest.cs创建时间: 2022.6.26文件功能描述: Copyright © 2022年 王银 All rights reserved.
----------------------------------------------------------------*/using System;
using System.IO;
using BestHTTP;
using UnityEngine;
using UnityEngine.UI;namespace BestHttpDemo
{public class BestHttpTest : MonoBehaviour{private Button button;private RawImage image;void Start(){button = transform.Find("Button (Legacy)").GetComponent<Button>();image = transform.Find("RawImage").GetComponent<RawImage>();button.onClick.AddListener(ButtonCallBack);OnGetRequest();OnPostRequest();}private void ButtonCallBack(){OnLoadImage();}//Get请求public void OnGetRequest(){string url = "https://wy3.bestshe.top/game/GetInfo.php?action=login&user=admin&pwd=admin";url = SetUrlTime(url);HTTPRequest request = new HTTPRequest(newUri(url), HTTPMethods.Get, OnRequestFinished);request.Send();}public string SetUrlTime(string url){string symbol = url.IndexOf("?") > -1 ? "&" : "?";url = string.Format("{0}{1}time={2}", url, symbol, string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now));return url;}//Post请求private void OnPostRequest(){string url = "https://wy3.bestshe.top/game/GetInfo.php";HTTPRequest request = new HTTPRequest(newUri(url), HTTPMethods.Post, OnRequestFinished);request.AddField("action", "login");request.AddField("user", "admin");request.AddField("pwd", "admin");request.AddField("time", string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now));request.Send();}//请求回调void OnRequestFinished(HTTPRequest request, HTTPResponse response){Debug.Log(response.DataAsText);}//下载图片 public void OnLoadImage(){new HTTPRequest(new Uri("https://wy3.bestshe.top/game/13.jpeg"), (request, response) =>{image.texture = response.DataAsTexture2D;//保存图片try{if (Application.platform == RuntimePlatform.Android){File.WriteAllBytes("jar:file://" + Application.persistentDataPath + "/13.jpeg", response.Data);}else{File.WriteAllBytes(Application.dataPath + "/13.jpeg", response.Data);}}catch (IOException e){Debug.LogError(e);}}).Send();}}
}

部分API

public void BestHttpAPI(){GeneralStatistics stats = HTTPManager.GetGeneralStatistics(StatisticsQueryFlags.All); //获取统计信息,统计类型全部BestHTTP.Caching.HTTPCacheService.IsSupported        //是否支持缓存(只读)stats.CacheEntityCount.ToString();                   //缓存对象个数stats.CacheSize.ToString("N0");                      //缓存总大小BestHTTP.Caching.HTTPCacheService.BeginClear();      //清空缓存BestHTTP.Cookies.CookieJar.IsSavingSupported        //是否支持保存Cookie(只读)stats.CookieCount.ToString();                       //Cookie个数stats.CookieJarSize.ToString("N0");                 //Cookie总大小BestHTTP.Cookies.CookieJar.Clear();                 //清空CookieHTTPManager.GetRootCacheFolder()                    //获取缓存和Cookies目录路径stats.Connections.ToString();                       //Http连接数stats.ActiveConnections.ToString();                 //激活的Http连接数stats.FreeConnections.ToString();                   //空闲的Http连接数stats.RecycledConnections.ToString();               //回收的Http连接数stats.RequestsInQueue.ToString();                   //Request请求在队列的数量BestHTTP.HTTPManager.OnQuit();                      //退出统计//缓存维护  缓存最大1mb,   删除2天前的缓存BestHTTP.Caching.HTTPCacheService.BeginMaintainence(new BestHTTP.Caching.HTTPCacheMaintananceParams( TimeSpan.FromDays(2),1 *1024*1024 ));//Cookie维护  删除7天前的Cookie并保持在最大允许大小内。BestHTTP.Cookies.CookieJar.Maintain();//获取Cookie集合List<Cookie> cookie = CookieJar.Get(new Uri("https://www.baidu.com/"));//Cookie的API很多cookie[0].Namecookie[0].Domain cookie[0].Value}*/原文链接:https://blog.csdn.net/u012322710/article/details/52860747

Unity用UnityWebRequest和 BestHttp的GET和POST表单提交,与php交互相关推荐

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

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

  2. Unity使用UnityWebRequest请求服务器json数据,webgl端服务器请求

    根据unity官方说的, WebGL 网络无法直接访问套接字 由于存在安全隐患,JavaScript 代码无法直接访问 IP 套接字来实现网络连接.因此,.NET 网络类(即 System.Net 命 ...

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

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

  4. Unity通过UnityWebRequest进行Http链接

    文章目录 前言 一.Get和Post请求 二.设置头文件的Get请求和Post请求 三.数据转换 总结 前言 最近需要用Unity做一款链接HTTP服务器的游戏,因此对自己所做的东西进行记录,方便自己 ...

  5. Unity 使用UnityWebRequest问题小结

    UnityWebRequest是自带的下载资源的api,优点显而易见:封装好,简单用,兼容性跨平台非常好.缺点也显而易见:可拓展性差 下载小文件通常使用下面的方法: public IEnumerato ...

  6. unity 使用UnityWebRequest读取Json文件

    一.Json模板类 [Serializable] public class Settings {[SerializeField]public int Sleep;//等其他属性 } 二.读取 usin ...

  7. unity 轻型UnityWebRequest 加载

    项目内需要从web服加载texture,整理了一版简单的纹理管理,包含加载,卸载,控制同时加载数量 1.封装一个LoadingTexture,包含开始下载,中断,callback,释放,是否正在下载, ...

  8. Unity 数据读写与存档(1)——配置表初探

    1.1 与策划小伙伴协同工作 如果大家在使用Unity的游戏公司工作,或者对游戏公司的工作流程与技术有所知晓,相信一定会或多或少地听说过"配置表"这个东西. 什么是配置表呢?很简单 ...

  9. svn如何删除服务器上的文件,【SVN】彻底 svn 服务器上的 删除某一个文件或文件夹...

    参考: CSDN1:https://blog.csdn.net/u011729865/article/details/78764523 CSDN2:https://blog.csdn.net/wyyo ...

最新文章

  1. linux中文麻酱字_【树】Linux笔记 1
  2. qt中定时器Timer的使用
  3. 最大公约数与最小公约数!_只愿与一人十指紧扣_新浪博客
  4. 安装python3.7和PyCharm专业版
  5. Spring的lazy-init详解
  6. Redis_简单使用
  7. 2017年2月20日 Random Forest Classifier
  8. 20应用统计考研复试要点(part33)--简答题
  9. 【深度学习】——纠错error: Unable to find vcvarsall.bat:关于安装pycocotools
  10. springboot——概述
  11. Java基础 - 变量的定义和使用
  12. AN EMPIRICAL STUDY OF EXAMPLE FORGETTING DURING DEEP NEURAL NETWORK LEARNING 论文笔记
  13. 微信小程序发送模板消息通知
  14. JS学习之Object
  15. 20200714一维数组的经典例题(成绩的最高分,最低分;猜中数字游戏;数组的增添改查;)
  16. 数据处理-倾斜摄影OSGB合并根节点
  17. mysql域是什么意思_MySQL--域
  18. Chrome浏览器标签管理插件–OneTab
  19. 小米12、小米12x和小米12pro的区别
  20. 曾国藩:一勤天下无难事(五勤)

热门文章

  1. java 车联网_车联网V2X开发
  2. 微软常用运行库合集 202206
  3. 【单片机毕业设计】【mcuclub-jj-015】基于单片机的风扇的设计
  4. Baidu Apollo代码解析之Planning的结构与调用流程(1)
  5. 1.cpt介绍与思科设备的基本配置
  6. itext 导出word
  7. Server 2016/Windows 10使用域管理员账户操作提示权限不足的问题
  8. 先进半导体材料与器件Chapter4
  9. p 车票提前下车客户端linux,火车能中途下车么?看完你就知道了
  10. java七行情书_七行情书