个人技术总结——Unity中对于Http的进一步封装

222000316谭楷 2023-06-08 20:51:27

技术概述

更简单的在Unity中使用Http方法。

这个技术是做什么的

用来更为优雅的实现对网络请求以及对后端数据的处理。

什么情况下会使用到这个技术

需要通过http方法从网络上请求数据时会用到。

学习该技术的原因

方便代码编写,是代码更为易懂,更为简洁。

技术的难点在哪里

cookie的设置,类本身的设计,以及对于易用性的考虑。

技术详述

img

img

img

基本思路就是将向协程中传入地址、序列化好的body以及处理响应结果的action。

对于登陆的问题,由于我自己测试时后端返回的setcookie无法生效,所以需要对登录token进行单独的获取。

image-20230608204616056

代码

public static IEnumerator PostWithHeader(string url, string content, Action action = null, string contentType = "application/json;charset=utf-8")
    {
        Debug.Log("GetWithHeader" + "<color=darkblue>" + content);
        UnityWebRequest www = UnityWebRequest.Post(url, content);
        byte[] bodyRaw = Encoding.UTF8.GetBytes(content);
        www.uploadHandler = new UploadHandlerRaw(bodyRaw);
        www.SetRequestHeader("Cookie", loginToken);

        www.SetRequestHeader("Content-Type", contentType);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Post on" + url + "Error" + www.responseCode);
        }
        else
        {
            Debug.Log("Post on" + url + "finished");
#if UNITY_EDITOR
            Debug.Log(www.downloadHandler.text);
#endif
            //T value = JsonConvert.DeserializeObject<Response<T>>(www.downloadHandler.text).data;
            action?.Invoke();
        }

    }
class Response<T>
{
    public int code { get; set; }
    public string msg { get; set; }
    public T data { get; set; }
}
    public IEnumerator LoginRequest(string url, string content, Action<string> messageHandler = null, string contentType = "application/json;charset=utf-8")
    {
        UnityWebRequest www = UnityWebRequest.Post(url, content);
        byte[] bodyRaw = Encoding.UTF8.GetBytes(content);
        www.uploadHandler = new UploadHandlerRaw(bodyRaw);
        www.SetRequestHeader("Content-Type", contentType);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Poston " + url + " Error " + www.responseCode);
        }
        else
        {
            Debug.Log("<color=green>Poston " + url + " finished");
#if UNITY_EDITOR
            Debug.Log(www.downloadHandler.text);
#endif
            string setCookie = www.GetResponseHeader("Set-Cookie");
            Debug.Log(setCookie.Substring(0,setCookie.IndexOf(";")));
            string value = JsonConvert.DeserializeObject<Response<UserResponse>>(www.downloadHandler.text).msg;
            GlobalData.userInfo = JsonConvert.DeserializeObject<Response<UserResponse>>(www.downloadHandler.text).data.user;
            Debug.Log(GlobalData.userInfo.name);
            if (value == "登录成功")
            {
                WebBase.loginToken = setCookie.Substring(0, setCookie.IndexOf(";"));
                eventCenter.EventTrigger<Action>("DialogAction", ActionToHomeScene);
            }
            messageHandler?.Invoke(value);
        }
    }

总结

由于本次项目功能特别多,所以需要在封装上多下一点功夫,不然庞大的代码我自己找起来都有些麻烦,于是就诞生了这个封装。我认为在今后的学习中还是要多多编写这样的功能组件,丰富自己的代码库。

...全文
255 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

587

社区成员

发帖
与我相关
我的任务
社区描述
软件工程-2022-23学年(第二学期)
软件工程 高校
社区管理员
  • LinQF39
  • chennuo.
  • 异梦1
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧