99 lines
2.9 KiB
C#
99 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Data;
|
|
using System.Drawing;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Net.Http;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Forms;
|
|
|
|
namespace Go_Frp
|
|
{
|
|
public partial class Login : Form
|
|
{
|
|
public Login()
|
|
{
|
|
InitializeComponent();
|
|
}
|
|
|
|
private void logout_but_Click(object sender, EventArgs e)
|
|
{
|
|
// 退出事件
|
|
Application.Exit();
|
|
}
|
|
|
|
private async void login_but_Click(object sender, EventArgs e)
|
|
{
|
|
// 登录事件
|
|
string username = username_text.Text;
|
|
string password = password_text.Text;
|
|
|
|
// 检查用户名和密码是否输入
|
|
if (username == "" || password == "")
|
|
{
|
|
ts_lab.ForeColor = Color.Red;
|
|
ts_lab.Text = "用户名或密码有误";
|
|
}
|
|
else
|
|
{
|
|
|
|
// 准备发送的数据
|
|
var loginData = new
|
|
{
|
|
username = username_text.Text,
|
|
password = password_text.Text
|
|
};
|
|
|
|
// 将数据发送到后端
|
|
String responseMessage = await SendLoginRequestAsync("http://localhost:8080/login", loginData);
|
|
|
|
if (responseMessage == "success")
|
|
{
|
|
// 登录成功后关闭当前窗口
|
|
this.Close();
|
|
}
|
|
else
|
|
{
|
|
ts_lab.ForeColor = Color.Red;
|
|
ts_lab.Text = "登录失败:" + responseMessage;
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task<string> SendLoginRequestAsync(string url, object data)
|
|
{
|
|
try
|
|
{
|
|
using (HttpClient client = new HttpClient())
|
|
{
|
|
// 将数据转化为 JSON
|
|
string jsonData = JsonSerializer.Serialize(data);
|
|
|
|
// 创建请求
|
|
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
|
|
|
|
// 发送 Post 请求
|
|
HttpResponseMessage response = await client.PostAsync(url, content);
|
|
|
|
// 确保响应成功
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
// 读取响应内容
|
|
string responseBody = await response.Content.ReadAsStringAsync();
|
|
|
|
// 返回后端消息响应。
|
|
return responseBody;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 错误处理
|
|
return "Error: " + ex.Message;
|
|
}
|
|
}
|
|
}
|
|
}
|