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);
相关推荐
梦想平凡1 小时前
网狐旗舰版源码搭建概览
游戏程序·源代码管理
超龄魔法少女20 小时前
[Unity] ShaderGraph动态修改Keyword Enum,实现不同效果一键切换
unity·技术美术·shadergraph
蔗理苦1 天前
2024-12-24 NO1. XR Interaction ToolKit 环境配置
unity·quest3·xr toolkit
花生糖@1 天前
Android XR 应用程序开发 | 从 Unity 6 开发准备到应用程序构建的步骤
android·unity·xr·android xr
向宇it1 天前
【从零开始入门unity游戏开发之——unity篇02】unity6基础入门——软件下载安装、Unity Hub配置、安装unity编辑器、许可证管理
开发语言·unity·c#·编辑器·游戏引擎
虾球xz1 天前
游戏引擎学习第55天
学习·游戏引擎
虾球xz1 天前
游戏引擎学习第58天
学习·游戏引擎
ue星空1 天前
虚幻引擎结构之UWorld
游戏引擎·虚幻
ue星空1 天前
虚幻引擎结构之ULevel
游戏引擎·虚幻
向宇it1 天前
【从零开始入门unity游戏开发之——unity篇01】unity6基础入门开篇——游戏引擎是什么、主流的游戏引擎、为什么选择Unity
开发语言·unity·c#·游戏引擎