unity webgl获取页面Token信息,及加载StreamingAssets下.txt


接收JS端传回的token信息,如:

jwt~eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cCI6MTY0MjEzODIyNCwidXNlcm5hbWUiOiIxMTkwMjA1MTY5In0.ucdrtqfwOpaEzQkMHOWY7S_nvSTgOroRPa2T9y3H4q0

或者UserInf信息,如:

userinfo~{"id":111,"mobile":"18400000000","password":null,"photo":null,"qq":null,"sex":0,"sn":"100100100","username":"刘X","clazzId":null,"clazzNo":"2021122801","roleId":1,"createDate":"2021-12-29T09:21:58","updateDate":null,"creator":null,"updater":null}

在打包出来的web文件内找到index,做如下修改unity webgl获取页面Token信息,及加载StreamingAssets下.txt_第1张图片

 

 在打包出来的web文件内找到UnityProgress文件(路径:TemplateData/UnityProgress),做如下修改unity webgl获取页面Token信息,及加载StreamingAssets下.txt_第2张图片

if (progress == 1)
{
    gameInstance.logo.style.display = gameInstance.progress.style.display = "none";
  	getLocalStorage();
  }
 }   
    function getLocalStorage(){
        //读取localStorage,并调用函数传递信息到C#
        JSCommand('jwt~' + storage.getItem('jwt'));
        JSCommand('userinfo~' + storage.getItem('userinfo'));
    }
    //JS向C#传递信息
    function JSCommand(str) {
        console.log("JSCommand--" + str);
        //三个参数:第一个参数是脚本所在物体名,第二个是脚本函数名,第三个是发送信息
        gameInstance.SendMessage('MainScript', 'JSFunction', str);
    }
		

接下来在场景中创建对象(名字:MainScript(根据js的填写进行修改)) ,添加脚本(名字:MainSceneManager(可任意起)),脚本内方法如下:

(对服务返回数据进行处理时需要导入Dll文件到Unity工程中
dll链接:链接:https://pan.baidu.com/s/1TdyJYOnicoDYxmvv5Md46A 
提取码:o0gx )

unity webgl获取页面Token信息,及加载StreamingAssets下.txt_第3张图片

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
using UnityEngine.Networking;
//使用json需要dll
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Runtime.InteropServices;

[System.Serializable]
public class TestData
{
    public string url_login;
    public string url_score;
}
public class MainSceneManager : MonoBehaviour
{
//该方法通过页面端调用  接收webgl的js传递的信息
string token = "";
string userInf = "";
string sn = "";
string classid = "";
public void JSFunction(string str)
    {
        public void JSFunction(string str)
        {
            Debug.LogWarning("接收js传递信息");
            string[] tmpArray = str.Split('~');
            if (tmpArray[0] == "jwt")
            {
                token = tmpArray[1];
                Debug.LogWarning("token--" + token);
                //token--eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cCI6MTY0MjEzODIyNCwidXNlcm5hbWUiOiIxMTkwMjA1MTY5In0.ucdrtqfwOpaEzQkMHOWY7S_nvSTgOroRPa2T9y3H4q0
            }
            if (tmpArray[0] == "userinfo")
            {
                //转换接收到数据,进行处理
                JObject tmpObj = (JObject)JsonConvert.DeserializeObject(tmpArray[1]);
                //{"id":111,"mobile":"18400000000","password":null,"photo":null,"qq":null,"sex":0,"sn":"100100100","username":"刘X","clazzId":null,"clazzNo":"2021122801","roleId":1,"createDate":"2021-12-29T09:21:58","updateDate":null,"creator":null,"updater":null}
                userInf = tmpArray[1];
                sn = tmpObj["sn"].ToString();
                classid = (int)tmpObj["clazzId"];
            }
        }
    }
}

当在网页端启动inde.html时,调用上述方法。

当获取的userinfo信息含有数组时,如:

{"code":0,"msg":"查询班级","timestamp":"2022-01-14 03:30:29","data":[{"username":"张3","id":1,"name":"计算机","info":null,"teacherSn":null,"function1":0,"function2":1,"function3":1,"createDate":"2021-12-29T09:22:35","creator":null,"updateDate":null,"updater":null,"clazzNo":"2021122801"},{"username":"张4","id":2,"name":"计算机","info":null,"teacherSn":null,"function1":1,"function2":1,"function3":1,"createDate":"2021-12-29T09:22:35","creator":null,"updateDate":null,"updater":null,"clazzNo":"2021122802"},{"username":null,"id":3,"name":"计算机","info":"2323","teacherSn":null,"function1":1,"function2":0,"function3":0,"createDate":"2021-12-31T11:35:11","creator":null,"updateDate":null,"updater":null,"clazzNo":"202112280刘"}],"ttl":null,"count":3}

可使用下述(加载StreamingAssets下。。。)中的方法进行处理;

加载StreamingAssets下urlID.txt获取服务器地址,携带token和服务器交互,获取跟多信息,并进行处理;

unity webgl获取页面Token信息,及加载StreamingAssets下.txt_第4张图片

unity webgl获取页面Token信息,及加载StreamingAssets下.txt_第5张图片

 上述urlID.txt内地址需要自己修改成需要地址;

如何加载web端StreamingAssets下urlID.txt,调用Unity_Get请求(携带Token)以及对获取到包含数组的字符串处理如下:

using System.Collections;
using UnityEngine;
using System;
using UnityEngine.Networking;
//使用json需要dll
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

[System.Serializable]
public class TestData
{
    public string url_login;
    public string url_score;
}
public class MainSceneManager : MonoBehaviour
{
    float timeStamp; //时间戳
    string token = "";//登陆成功后token值
    string sn = "";
    int classid;
    int func1;
    int func2;
    int func3;
    string url_login = "";   //获取Get请求地址
    string url_score = "";    //上传数据地址
    void Start()
    {
        System.TimeSpan st = System.DateTime.UtcNow - new System.DateTime(1970, 1, 1, 0, 0, 0);//获取时间戳Debug.Log(Convert.ToInt64(st.TotalSeconds) );//时间戳转换Int64
        timeStamp = Convert.ToInt64(st.TotalMinutes);
    }
    // 接收webgl的js传递的信息
    public void JSFunction(string str)
    {
        Debug.LogWarning("接收js传递信息");
        string[] tmpArray = str.Split('~');
        if (tmpArray[0] == "jwt")
        {
            token = tmpArray[1];
            Debug.LogWarning("token--" + token);
            Data.token = token;
        }
        if (tmpArray[0] == "userinfo")
        {
            JObject tmpObj = (JObject)JsonConvert.DeserializeObject(tmpArray[1]);
            sn = tmpObj["sn"].ToString();
            classid = (int)tmpObj["clazzNo"];
            StartCoroutine(Get_UrlData());
        }
    }
   
    //通过urlID.txt 查找地址
    IEnumerator Get_UrlData()
    {
        Debug.Log("加载streamingAssets下urlID.txt");
        var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "urlID.txt"));
        UnityWebRequest www = UnityWebRequest.Get(uri);
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log(www.downloadHandler.text);
            string jsonStr = www.downloadHandler.text;
            TestData testData = JsonUtility.FromJson(jsonStr);
            url_login = testData.url_login;
            url_score = testData.url_score;
            StartCoroutine(Get_AllData());
        }
    }
    //通过token 查找信息 
    IEnumerator Get_AllData()
    {
        UnityWebRequest www = UnityWebRequest.Get(Data.url_login);
        www.SetRequestHeader("admin-token", Data.token);
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log(www.downloadHandler.text);
            //返回数据string转json对象
            JObject tmpObj = (JObject)JsonConvert.DeserializeObject(www.downloadHandler.text);
            JArray jArray = (JArray)tmpObj["data"];
            Debug.Log("jArray.Count--" + jArray.Count);
            for (var i = 0; i < jArray.Count; i++)
            {
                JObject jo2 = (JObject)jArray[i];
                if ((int)(jo2["clazzNo"]) == classid)
                {
                    func1 = Convert.ToInt32(jo2["function1"]);
                    func2 = Convert.ToInt32(jo2["function2"]);
                    func3 = Convert.ToInt32(jo2["function3"]);
                }
            }
        }
    }
}

 若想主动发起请求可参考:unity 发送消息与web前端交互_Monkey_Xuan的博客-CSDN博客

你可能感兴趣的:(unity,游戏引擎)