105 lines
2.9 KiB
C#
105 lines
2.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
using System.Threading.Tasks;
|
|
using System;
|
|
|
|
|
|
|
|
public class LoginAndGetToken : MonoBehaviour
|
|
{
|
|
public delegate void TokenReceivedDelegate(string token);
|
|
public static event TokenReceivedDelegate OnTokenReceived;
|
|
|
|
private void OnEnable()
|
|
{
|
|
//Login();
|
|
}
|
|
|
|
public async void Login()
|
|
{
|
|
// ... 登录逻辑 ...
|
|
loginbody body = new loginbody();
|
|
body.userName = "15151658596";// + 15151658596;
|
|
body.password = "123456";// + 123456;
|
|
body.verifyCode = 111111;
|
|
string loginResponse = await web.SendRequest("http://121.40.42.41:8080/snail/user/login", "POST", JsonUtility.ToJson(body));
|
|
//Debug.Log("LoginAndGetToken登录:"+loginResponse);
|
|
string token = getToken(loginResponse);
|
|
OnTokenReceived?.Invoke(token);
|
|
//登录请求//已通过
|
|
}
|
|
public static string getToken(string json)
|
|
{
|
|
try
|
|
{
|
|
// 解析JSON字符串为JObject
|
|
JObject parsedJson = JObject.Parse(json);
|
|
|
|
// 从JObject中提取token字段的值
|
|
string token = parsedJson["data"]?["token"]?.ToString();
|
|
|
|
// 返回token
|
|
return token;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 处理解析过程中可能出现的异常
|
|
Console.WriteLine("An error occurred while parsing the JSON: " + ex.Message);
|
|
return null;
|
|
}
|
|
}
|
|
[Serializable]
|
|
public class loginbody//登录和注册用
|
|
{
|
|
public string userName;
|
|
public string password;
|
|
public int verifyCode;
|
|
|
|
}
|
|
}
|
|
/*public class LoginAndGetToken : MonoBehaviour
|
|
{
|
|
private static LoginAndGetToken _instance;
|
|
public static LoginAndGetToken Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
GameObject obj = new GameObject("LoginAndGetToken");
|
|
_instance = obj.AddComponent<LoginAndGetToken>();
|
|
DontDestroyOnLoad(obj); // 确保单例在场景加载时不会被销毁
|
|
}
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
private string _token;
|
|
|
|
public async void Login()
|
|
{
|
|
loginbody body = new loginbody();
|
|
body.userName = "15151658596";
|
|
body.password = "123456";
|
|
body.verifyCode = 111111;
|
|
string loginResponse = await web.SendRequest("http://121.40.42.41:8080/snail/user/login", "POST", JsonUtility.ToJson(body));
|
|
Debug.Log(loginResponse);
|
|
_token = getToken(loginResponse);
|
|
}
|
|
|
|
public static string GetToken()
|
|
{
|
|
return Instance._token;
|
|
}
|
|
|
|
public static string getToken(string loginResponse)
|
|
{
|
|
JObject jsonObject = JObject.Parse(loginResponse);
|
|
string token = (string)jsonObject["data"]?["token"];
|
|
Debug.Log(token);
|
|
return token;
|
|
}
|
|
}*/ |