Unity后台登录/获取数据——BestHTTP的使用Get/Post

一、使用BestHTTP实现登录功能(Post)

登录具体的步骤如下:
1:传入你的用户名和密码,这是一条包括链接和用户名密码的链接
2:使用BestHTTP的Post功能将链接传到服务器后台
3:后台拿到了你传送的包括用户名和密码的链接以后,解析用户名和密码,和数据库中的内容进行比对
4:如果是匹配的就返回true,如果补匹配就返回false

具体的代码如下:

using UnityEngine;
using System;
using BestHTTP;
using LitJson;
using Cysharp.Threading.Tasks;

public class ServerManager : Singleton
{
    private string root = "http://*************************************";
    private ResponseResult response;
    public ResponseResult Response
    {
        get => response;
    }
    
    /// 
    /// 使用异步操作加载
    /// 
    /// 
    /// 
    /// 
    public async UniTask Login(string username, string password)
    {
        var url = $"{root}?username={username}&password={password}";
        HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Post);
        await request.Send();
        if (request.Exception != null)
        {
            Debug.Log("请求异常" + request.Exception.Message);
            return false;
        }
        else if (request.Response.IsSuccess)
        {
            Debug.Log("response success!");
            string stringResponse = request.Response.DataAsText;
            response = JsonMapper.ToObject(stringResponse);
            bool isSuccess = response.success;
            Debug.Log(isSuccess);
            Debug.Log(response.result);
            return isSuccess;
        }
        return false;
    }
}
public abstract class Singleton where T : new()
{
    private static T _instance;
    private static object _lock = new object();
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                    }
                }
            }
            return _instance;
        }
    }
}
public class ResponseResult
{
    public bool success;
    public string errorMessage;
    public object data;
    public string result;
}
private string root = "http://*********";

这是你后台链接,就是你们的服务器IP地址

var url = $"{root}?username={username}&password={password}";

使用字符串拼接把服务器的地址和你的用户名密码拼接在一起,组成一条链接

HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Post);
await request.Send();

使用BestHTTP插件把刚才的Url链接Post上去,注意使用HTTPMethods.Post方法,这里因为使用了异步,所以直接用await,不用使用回调函数

string stringResponse = request.Response.DataAsText;
response = JsonMapper.ToObject(stringResponse);

这里使用一个字符串从服务器获取到你的内容,然后使用LitJson解析下内容

bool isSuccess = response.success;

后台写好的bool,可以用来判断是否登陆成功

然后登录界面就很简单了

private async void  OnLoginBtnClick()
    {
        var res = await ServerManager.Instance.Login(UserField.text, PasswordField.text);
        if (!res)
        {
            StartCoroutine(WrongText());
        }
        else
        {
            SceneManager.LoadScene(1);
        }
    }

直接判断你返回的bool就好了!

二、使用BestHTTP实现从后台获取数据(Get)

这个原理和上面是一样的,不过只是get数据

1:传入你的url链接到BestHTTP
2:使用回调函数来执行请求后的操作
3:使用匹配的数据类来解析内容

具体的代码如下:

private string dataURL = "http://cottonhouse.tianfuchuang.cn/admin/data/getData";
 private IEnumerator SendRequest()
    {
        HTTPRequest request = new HTTPRequest(new System.Uri(dataURL), OnRequestFinished);
        request.Send();
        yield break;
    }

    private void OnRequestFinished(HTTPRequest request, HTTPResponse response)
    {
        if (request.Exception != null)
        {
            Debug.Log("请求异常" + request.Exception.Message);
            return;
        }

        try
        {
            if (response.IsSuccess)
            {
            Debug.Log("response success!");
            //转为text
            string stringResponse = response.DataAsText;

            //转为二进制数组
            //byte[] results = response.Data;

            //以WebDataClass的数据类来解析获取到的数据
            dataClass = JsonMapper.ToObject(stringResponse);
            if (dataClass != null)
            {
                Debug.Log("解析成功");
             }
}
}

这里的代码和上面的不同是,这里采用了回调函数OnRequestFinished()

其他是一样的

以上就是使用BestHTTP插件实现Post和Get操作的功能!

你可能感兴趣的:(C#,Unity引擎,unity)