WXMC/.svn/pristine/2f/2ff19728fac22843b6c0121091379d9d7d30946a.svn-base
2024-12-04 16:18:46 +08:00

61 lines
1.5 KiB
Plaintext

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class NetWorkManager : MonoSingletion<NetWorkManager>
{
private string ip = "http://114.132.68.192:8881";
public void Login(string username, string password) {
StartCoroutine(SendLogin(username, password));
}
private IEnumerator SendLogin(string username, string password)
{
string url = ip + "/api/user/login";
LoginData data = new LoginData();
data.username = username;
data.password = password;
string json = JsonUtility.ToJson(data);
// 转换JSON数据到字节
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
// 创建UnityWebRequest对象
UnityWebRequest www = new UnityWebRequest(url, "POST");
// 设置请求头
www.SetRequestHeader("Content-Type", "application/json");
// 设置POST数据
www.uploadHandler = new UploadHandlerRaw(jsonToSend);
www.downloadHandler = new DownloadHandlerBuffer();
// 发送请求并等待响应
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Login successful! Response: " + www.downloadHandler.text);
}
}
}
[System.Serializable]
public class LoginData {
public string username;
public string password;
}