热门IT资讯网

Unity 中Token的应用

发表于:2024-11-21 作者:热门IT资讯网编辑
编辑最后更新 2024年11月21日,using UnityEngine;using System;using System.Collections;using System.Net;using System.Text;using Sys
using UnityEngine;using System;using System.Collections;using System.Net;using System.Text;using System.Web;public class GainToken : MonoBehaviour {         // Use this for initialization        void Start () {                         }            public string content;    private string GetToken()    {        string xml = "............";//提供的XML/Json数据        try        {            byte[] data = Encoding.Default.GetBytes(xml);            string url = "..........";//提供获取Token值的服务地址(很重要)                        //如果不了解HttpWebRequest类,进入网址https://msdn.microsoft.com/zh-cn/library/system.net.httpwebresponse.aspx查询            HttpWebRequest requst = (HttpWebRequest)WebRequest.Create(url);//获取            requst.Method = "POST";//请求服务的方式            System.IO.Stream sm = requst.GetRequestStream();//Web请求            sm.Write(data, 0, data.Length);//XML数据            sm.Close();            HttpWebResponse response = (HttpWebResponse)requst.GetResponse();//响应WebResponse从互联网上的资源。            System.IO.Stream streamResponse = response.GetResponseStream();                         //获取到的Token值            System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse, Encoding.UTF8);            Char[] readBuff = new Char[256];//字节数            int count = streamRead.Read(readBuff, 0, 256);            //转换Token值为string形式            while (count > 0)            {                string outputData = new string(readBuff, 0, count);                content += outputData;                count = streamRead.Read(readBuff, 0, 256);            }            response.Close();//关闭Token值请求(一定要关闭,要不然会程序会死掉)        }        catch (System.Exception ex)        {            ex.ToString();                }         return content;    }            接下来,通过获取的token值,得到URL ="http://" + ip:port + "..." + token +"....";        通过WWW类和协程获取服务器上的数据,解析。。。。。。        下面的东西就不说了,很简单的!!            补充一个知识:获取下来的字符串有些是多余的,我们可以将多余的摘掉,     public static string GetTokenXML(string str, string startStar, string endStr)    {        int start = str.IndexOf(startStar);        int end = str.IndexOf(endStr);        int leng = end - (start + startStar.Length);        if (start == -1)        {            return "";        }        else if (end == -1)        {            return "";        }        else        {            return str.Substring(start + startStar.Length, leng);        }    }



0