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

目录

在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;
    //要替换背景的RawImage
    public RawImage testholder;
    //点击左边这个按钮,显示默认占位图
    public Button setDefaultImage;
    //点击这个按钮,从Web服务器加载图片显示在上面的RawImage
    public 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(new
                Uri(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(new
                Uri(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();                 //清空Cookie
     
        HTTPManager.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].Name
        cookie[0].Domain 
        cookie[0].Value
    }
    */

原文链接:https://blog.csdn.net/u012322710/article/details/52860747

猜你喜欢

转载自blog.csdn.net/hack_yin/article/details/125091499