Unity组件开发--短连接HTTP

1.网络请求管理器

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中添加

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);
            }

        }
    }
}

引用路径:

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中添加

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));
    }

引用路径:

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中添加

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();

}

引用路径:

        HttpHelper.Instance.DeleteMessage(() =>
        {
            ToastPanel.Show("留言删除成功");
            currentBoard.records.Remove(delData);
            OnRefresh();
        }, delData.id);

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小春熙子

你一毛我一毛,先富带后富

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值