wangguan
2020-11-30 e45603a605b359a790f91822d76a5e5e49b3d5c6
HTTP辅助类
2 files added
3 files modified
269 ■■■■■ changed files
Assets/Scripts/Common/GameConfig.cs 3 ●●●●● patch | view | raw | blame | history
Assets/Scripts/Common/HttpHelper.cs 109 ●●●●● patch | view | raw | blame | history
Assets/Scripts/Common/HttpHelper.cs.meta 11 ●●●●● patch | view | raw | blame | history
Assets/Scripts/GameAnalytics_SDK/UI/LoginUI.cs 2 ●●●●● patch | view | raw | blame | history
Assets/Scripts/Guide/TestButton.cs 144 ●●●●● patch | view | raw | blame | history
Assets/Scripts/Common/GameConfig.cs
@@ -26,6 +26,9 @@
        public static bool OpenDebug = false;
        public static string PlayerName = "";
        /// <summary>
        /// PVE无尽模式,是否可以点击购买新的宝石
        /// </summary>
Assets/Scripts/Common/HttpHelper.cs
New file
@@ -0,0 +1,109 @@

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class HttpHelper
{
    public enum MethodType
    {
        GET,
        POST
    }
    public class DownloadHanlderType
    {
        public const string kHttpBYTE = "BYTE";
        public const string kHttpTEXT = "TEXT";
    }
    public static void Request(MonoBehaviour mono, string url, MethodType method, Dictionary<string, object> form, Action<object> callback, string responseType)
    {
        if (method == MethodType.GET)
        {
            url = CreateGetData(url, form);
            mono.StartCoroutine(Request(url, null, callback, responseType));
        }
        else if (method == MethodType.POST)
        {
            WWWForm formData = CreatePostData(form);
            mono.StartCoroutine(Request(url, formData, callback, responseType));
        }
        else
        {
            Debug.LogError("你不能这样子哦...");
        }
    }
    static IEnumerator Request(string url, WWWForm form, Action<object> callback, string dateType)
    {
        UnityWebRequest request = null;
        if (form == null)
            request = UnityWebRequest.Get(url);
        else
        {
            request = UnityWebRequest.Post(url, form);
        }
        yield return request.SendWebRequest();
        if (request.isHttpError || request.isNetworkError)
        {
            Debug.LogErrorFormat("Request Error: {0}", request.error);
        }
        if (request.isDone)
        {
            if (dateType == DownloadHanlderType.kHttpTEXT)
            {
                callback?.Invoke(request.downloadHandler.text);
            }
            else if (dateType == DownloadHanlderType.kHttpBYTE)
            {
                callback?.Invoke(request.downloadHandler.data);
            }
            else
            {
                Debug.LogError("你不能这样子哦...");
            }
        }
    }
    private static string CreateGetData(string url, Dictionary<string, object> form)
    {
        string data = "";
        if (form != null && form.Count > 0)
        {
            foreach (var item in form)
            {
                data += item.Key + "=";
                data += item.Value.ToString() + "&";
            }
        }
        if (url.IndexOf("?") == -1)
            url += "?";
        else
            url += "&";
        url += data.TrimEnd(new char[] { '&' });
        return url;
    }
    private static WWWForm CreatePostData(Dictionary<string, object> formData)
    {
        WWWForm form = new WWWForm();
        if (formData != null && formData.Count > 0)
        {
            foreach (var item in formData)
            {
                if (item.Value is byte[])
                    form.AddBinaryData(item.Key, item.Value as byte[]);
                else
                    form.AddField(item.Key, item.Value.ToString());
            }
        }
        return form;
    }
}
Assets/Scripts/Common/HttpHelper.cs.meta
New file
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 09e53cb106447414fb8bd08e6985d9c2
MonoImporter:
  externalObjects: {}
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:
Assets/Scripts/GameAnalytics_SDK/UI/LoginUI.cs
@@ -63,6 +63,8 @@
            imei0 = "MyTestGemBattle123";
        }
        GameConfig.PlayerName = imei0;
        versionTxt.text = "版本号:" + Application.version;
        //resVersion.text 暂时没有使用
        transform.Find("Panel/PlayerID").GetComponent<Text>().text = "玩家ID:" + imei0;
Assets/Scripts/Guide/TestButton.cs
@@ -3,6 +3,12 @@
using UnityEngine;
using UnityEngine.UI;
using KTGMGemClient;
using LitJson;
using UnityEngine.Networking;
using System.Net;
using System.IO;
using System.Collections.Generic;
public class TestButton : MonoBehaviour
{
    //public Text t;
@@ -19,8 +25,133 @@
        // string s="<color=red>范围伤害</color>";
        // t.text=s;
        // Debug.Log(s.Length);
        TestFinalPanel();
        //TestFinalPanel();
        isSending = false;
        TestHttp();
    }
    private void OnGUI()
    {
        GUILayout.BeginArea(new Rect(5, 330, 150, 300));
        if (GUILayout.Button("SendRequest", GUILayout.Width(150), GUILayout.Height(70)))
        {
            //SendRequest("aa", 4700, 28);
            SendPost("aaa", 7890, 1);
        }
        if (GUILayout.Button("SendGet", GUILayout.Width(150), GUILayout.Height(70)))
        {
            SendGet();
        }
        GUILayout.EndArea();
    }
    private JsonData loginData;
    public string imei0 = "";//设备信息唯一ID
    private bool isSending = false;
    void TestHttp()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            //GetetDeviceIMEI();//获取安卓手机IMEI
            imei0 = TDAA_SDKManager.Ins.GetDeviceId();//使用设备ID
        }
        else if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            imei0 = "MyTestGemBattle123";
        }
        Debug.Log("设置imei0:" + imei0);
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="nickname"></param>
    /// <param name="score"></param>
    /// <param name="level"></param>
    private void SendPost(string nickname, int score, int level)
    {
        Debug.Log("开始Post");
        string url = "http://9377-big-data.sbk-h5.com:8600/users/addrank";
        Dictionary<string, object> keyValues = new Dictionary<string, object>();
        keyValues.Add("username", imei0);
        keyValues.Add("nickname", nickname);
        keyValues.Add("score", score);
        keyValues.Add("level", level);
        HttpHelper.Request(this, url, HttpHelper.MethodType.POST, keyValues, delegate (object value)
        {
            if (value != null)
                LoadPostTxt(value.ToString());
        }, HttpHelper.DownloadHanlderType.kHttpTEXT);
    }
    private void LoadPostTxt(string value)
    {
        Debug.Log(value);
        loginData = JsonMapper.ToObject(value);
        if (loginData["error"].ToString() != "0")
        {
            Debug.Log("失败了");
        }
        else if (loginData["msg"].ToString() == "OK")
        {
            Debug.Log("成功了");
            SendGet();
        }
    }
    /// <summary>
    /// 下载排行榜
    /// </summary>
    private void SendGet()
    {
        string url = "http://9377-big-data.sbk-h5.com:8600/users/getrank";//9377-big-data.sbk-h5.com:8600/users/getrank?username=0001&limit=100
        Dictionary<string, object> keyValues = new Dictionary<string, object>();
        keyValues.Add("username", imei0);
        keyValues.Add("limit", 100);
        HttpHelper.Request(this, url, HttpHelper.MethodType.GET, keyValues, delegate (object value)
        {
            if (value != null)
                LoadGetTxt(value.ToString());
        }, HttpHelper.DownloadHanlderType.kHttpTEXT);
    }
    private void LoadGetTxt(string value)
    {
        JsonData getData = JsonMapper.ToObject(value);
        int myrank = int.Parse(getData["myrank"].ToString());
        JsonData rank = getData["rank"];
        List<HttpGetInfo> allHttpGetInfoLis = new List<HttpGetInfo>();
        foreach (JsonData item in rank)
        {
            allHttpGetInfoLis.Add(
                new HttpGetInfo
                {
                    id = int.Parse(item["id"].ToString()),
                    username = item["username"].ToString(),
                    nickname = item["nickname"].ToString(),
                    score = int.Parse(item["score"].ToString()),
                    level = int.Parse(item["level"].ToString()),
                    extra = item["extra"],
                    create_time = int.Parse(item["create_time"].ToString()),
                }
            );
        }
        foreach (HttpGetInfo item in allHttpGetInfoLis)
        {
            Debug.Log($"item.username:{item.username}  item.nickname:{item.nickname} item.score:{item.score}  item.create_time:{item.create_time}");
        }
    }
    void TestFinalPanel()
    {
@@ -153,3 +284,14 @@
    }
}
public class HttpGetInfo
{
    public int id;
    public string username;
    public string nickname;
    public int score;
    public int level;
    public JsonData extra;
    public int create_time;
}