Unity组件开发--短连接HTTP

1.网络请求管理器

cs 复制代码
using LitJson;
using Cysharp.Threading.Tasks;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Events;

using System.Web;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using UnityEngine.Purchasing.MiniJSON;

public class HttpHelper : MonoBehaviour {
    public static HttpHelper Instance;

    [DllImport("__Internal")] public static extern string GetUrlParam(string str);
    private void Awake() {
        Instance = this;

    }


    enum HttpEnum {
        POST,
        GET,
        DEL
    }

UnityWebRequest requestHttp(string url, HttpEnum httpEnum, WWWForm form = null) {

    if (httpEnum == HttpEnum.GET) {
        Debug.Log($"url Get:{url}");
        return UnityWebRequest.Get(url);
    }
    else if (httpEnum == HttpEnum.POST) {
        Debug.Log($"url POST:{url}");
        return UnityWebRequest.Post(url, form);
    }
    else if (httpEnum == HttpEnum.DEL) {
        Debug.Log($"url Delete:{url}");
        return UnityWebRequest.Delete(url);
    }
    return null;
}

}

2.需要引入json数据解析的插件:LitJson

3.POST请求:HttpHelper中添加

cs 复制代码
public void GetUserInfo(string userId, UnityAction<string, bool> webHttpBack) {
    StartCoroutine(ccGetUserInfo(userId, webHttpBack));
}


IEnumerator ccGetUserInfo(string userId, UnityAction<string, bool> getInfoBack) {
    var url = Host.ApiHost + "/user/getUsrInfo";
    WWWForm form = new WWWForm();


    form.AddField("id", userId);
    using (UnityWebRequest www = requestHttp(url, HttpEnum.POST, form)) {
        DownloadHandler downloadHandler = new DownloadHandlerBuffer();
        www.downloadHandler = downloadHandler;



        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success) {
            Debug.LogError(www.error);
        }
        else {
            Debug.Log($"Form upload complete GetCurSpaceInfo! {www.downloadHandler.text}");
            JsonData data = JsonMapper.ToObject(www.downloadHandler.text);
            if (data["data"] != null) {
                string json = data["data"].ToJson();
                if (getInfoBack != null) getInfoBack(json, false);
            }
            else {
                if (getInfoBack != null) getInfoBack(null, true);
            }

        }
    }
}

引用路径:

cs 复制代码
if (HttpHelper.Instance != null) {
    HttpHelper.Instance.GetUserInfo(PlayerData.Instance.PlayerId.ToString(), getUserInfo);
}


public void getUserInfo(string json, bool isNoData)
{
    json = UtilsFunc.UnicodeToString(json);
    JsonData data = JsonMapper.ToObject(json);
    string headUrl = "";

    

    if (data.ContainsKey("headImgUrl") && data["headImgUrl"] != null)
    {
        headUrl = (string)data["headImgUrl"];
        Debug.Log("头像信息2222222222" + headUrl);
        StartCoroutine(loadHeadImgUrl(headUrl));
    }
}

4.GET请求:HttpHelper中添加

cs 复制代码
public IEnumerator coGetMessBoardList(Action callback, long startDate, long endDate, int page = 1, int limit = 20) {



    //var url = NetManager.Instance.host + ":":"+port+"/game/space/getSpace";
    string url = Host.ApiHost + "/message/board/list" + $"?page={page}&limit={limit}&startDate={startDate}&endDate={endDate}&spaceId={PlayerData.Instance.SpaceId}";
    using (UnityWebRequest www = requestHttp(url, HttpEnum.GET)) {
        www.SetRequestHeader("Authorization", PlayerData.Instance.ltk);
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.Success) {
            string text = www.downloadHandler.text;
            JsonData data = JsonMapper.ToObject(www.downloadHandler.text);
            string json = data["data"].ToJson();
            var listObj = JsonMapper.ToObject<BoardVo>(json);
            MessageBoardModel.Instance.m_BoardModel.Remove(1); //临时删除1
            MessageBoardModel.Instance.m_BoardModel.Add(1, listObj);
            Debug.Log("获取留言列表信息" + text);
        }
        else {
            Debug.LogError(www.error);
        }
    }
    callback.Invoke();
}


    public void GetMessBoardList(Action callback, long startDate, long endDate, int page = 1, int limit = 20) {
        StartCoroutine(coGetMessBoardList(callback, startDate, endDate, page, limit));
    }

引用路径:

cs 复制代码
HttpHelper.Instance.GetMessBoardList(() =>
{
    MessageBoardModel.Instance.m_BoardModel.TryGetValue(1, out currentBoard); //这里1是临时的,因为现在留言板就一块
    if (currentBoard == null)
    {
        Debug.LogError("OnEnter currentBoard == null");
        return;
    }
    OnRefresh();
}, current, oneMonthLater);

4.DEL请求:HttpHelper中添加

cs 复制代码
IEnumerator coGetShopUrl(string genUrl, Action<string> callback) {

    //获取商店链接
    Debug.Log($"{genUrl}");
    string url = $"https://api.qrserver.com/v1/create-qr-code/?size=150x150{genUrl}";
    using (UnityWebRequest www = requestHttp(url, HttpEnum.DEL)) {
        www.downloadHandler = new DownloadHandlerBuffer();
        www.SetRequestHeader("Authorization", PlayerData.Instance.ltk);


        yield return www.SendWebRequest();


        if (www.result == UnityWebRequest.Result.Success) {


            Debug.Log("商店链接:" + www.downloadHandler.text);

            string s = www.downloadHandler.text.Substring(www.downloadHandler.text.IndexOf("<img src=") + 12, www.downloadHandler.text.Length - (www.downloadHandler.text.IndexOf("<img src=") + 12));
            //截取src="" 内部的链接地址,不包括'//'
            string result = s.Substring(0, s.IndexOf("\""));

            callback.Invoke("https://" + result);
        }
        else {
            Debug.LogError(www.error);
            callback.Invoke(www.error);
        }
    }


}

    public void GetShopUrl(string url, Action<string> callback) {
        StartCoroutine(coGetShopUrl(url, callback));
    }

        public void DeleteMessage(Action callback, int id) {
        StartCoroutine(coDeleteMessage(callback, id));
    }


public IEnumerator coDeleteMessage(Action callback, int id) {



    string url = Host.ApiHost + "/message/board?id=" + id.ToString();
    using (UnityWebRequest www = requestHttp(url, HttpEnum.DEL)) {
        www.downloadHandler = new DownloadHandlerBuffer();
        www.SetRequestHeader("Authorization", PlayerData.Instance.ltk);


        yield return www.SendWebRequest();


        if (www.result == UnityWebRequest.Result.Success) {


            Debug.Log("删除留言信息" + www.downloadHandler.text);
        }
        else {
            Debug.LogError(www.error);
        }
    }

    callback.Invoke();

}

引用路径:

cs 复制代码
        HttpHelper.Instance.DeleteMessage(() =>
        {
            ToastPanel.Show("留言删除成功");
            currentBoard.records.Remove(delData);
            OnRefresh();
        }, delData.id);
相关推荐
charon87786 小时前
UE ARPG | 虚幻引擎战斗系统
游戏引擎
小春熙子8 小时前
Unity图形学之Shader结构
unity·游戏引擎·技术美术
Sitarrrr10 小时前
【Unity】ScriptableObject的应用和3D物体跟随鼠标移动:鼠标放置物体在场景中
3d·unity
极梦网络无忧10 小时前
Unity中IK动画与布偶死亡动画切换的实现
unity·游戏引擎·lucene
逐·風18 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
_oP_i19 小时前
Unity Addressables 系统处理 WebGL 打包本地资源的一种高效方式
unity·游戏引擎·webgl
代码盗圣1 天前
GODOT 4 不用scons编译cpp扩展的方法
游戏引擎·godot
Leoysq1 天前
【UGUI】实现点击注册按钮跳转游戏场景
游戏·unity·游戏引擎·ugui
PandaQue1 天前
《潜行者2切尔诺贝利之心》游戏引擎介绍
游戏引擎
_oP_i1 天前
unity中 骨骼、纹理和材质关系
unity·游戏引擎·材质