Unity http协议连接封装简易版(已测试可用)

项目中代码类:删除部分没用的代码,可以直接使用,代码中的json解析可以从网络上下载,

本人上传地址:https://download.csdn.net/download/leo347/85403901

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using Newtonsoft.Json.Linq;
using UnityEngine.Networking;
using System.Net;
using System.IO;
using System;
using System.Text;

/// 
/// 网络连接类简陋版,为保密项目,已删除部分真实服务器数据等。
/// 
public class NetClient : MonoBehaviour
{
    public static NetClient instance;
    private void Awake()
    {
        instance = this;
    }

    private string webURL = "服务器地址";
    private string apiURL = "";
    private string appId = "*****";//*****项目中用到,可以去除

    /// 
    /// 连接状态
    /// 
    public enum connectState
    {
        None,
        Register,//注册
        Login,//登陆
        GetCode,//获得验证码
        GetGold,//获得金币
        ConsumeGold,//消耗金币
        ResetPassword,//设置新密码
        RetrievePassword,//找回密码发送邮件
        AddGold,//增加金币,google充值

        phone,
        score,
        login2,
        users,
    }

    /// 
    /// 当前连接状态
    /// 
    private connectState currentState = connectState.None;

    #region 属性

    public bool IsBusy = false;//用于检测是否重复发送

    #endregion

 
    /// 
    /// 开始连接服务器
    /// 
    /// 
    public void Client(connectState _state)
    {
        if (!IsBusy)
        {
            Utils.Log("start connectting......"+ _state);
            IsBusy = true;
            currentState = _state;
            JsonData dataJson = new JsonData();//写入json格式的数据
            byte[] postBytes;
            switch (_state)
            {
                case connectState.Register:
                    apiURL = "API地址";
                    dataJson["account"] = DataLogin.instance.GetUserAccount();
                    dataJson["code"] = DataLogin.instance.GetCode();
                    dataJson["pwd"] = DataLogin.instance.GetUserPassword();
                    postBytes = System.Text.Encoding.Default.GetBytes(dataJson.ToJson());//把json格式的字符串转化成数组
                    StartCoroutine(ConnectPost(webURL + apiURL, postBytes,0));
                    break;
                case connectState.Login:
                    apiURL = "API地址";
                    dataJson["account"] = DataLogin.instance.CurAccount;
                    dataJson["pwd"] = DataLogin.instance.CurPassword;
                    postBytes = System.Text.Encoding.Default.GetBytes(dataJson.ToJson());//把json格式的字符串转化成数组
                    StartCoroutine(ConnectPost(webURL + apiURL, postBytes, 0));
                    break;
                case connectState.GetCode:
                    apiURL = "API地址";
                    StartCoroutine(ConnectGet(webURL + apiURL + "?account=" + DataLogin.instance.GetUserAccount()));
                    break;
                case connectState.GetGold:
                    apiURL = "API地址";
                    StartCoroutine(ConnectGet(webURL+apiURL+ "?userId="+DataLogin.instance.GetUserID()));
                    break;
                case connectState.ConsumeGold:
                    apiURL = "API地址";
                    dataJson["gold"] = DataLogin.instance.CurGoldConsumeNum;
                    dataJson["userId"] = DataLogin.instance.GetUserID();
                    postBytes = System.Text.Encoding.Default.GetBytes(dataJson.ToJson());//把json格式的字符串转化成数组
                    StartCoroutine(ConnectPost(webURL + apiURL, postBytes, 0));
                    break;
                case connectState.ResetPassword:
                    apiURL = "API地址";
                    dataJson["code"] = DataLogin.instance.CurCode;
                    dataJson["pwd"] = DataLogin.instance.CurPassword;
                    dataJson["account"] = DataLogin.instance.CurAccount;
                    postBytes = System.Text.Encoding.Default.GetBytes(dataJson.ToJson());//把json格式的字符串转化成数组
                    StartCoroutine(ConnectPost(webURL + apiURL, postBytes, 0));
                    break;
                case connectState.RetrievePassword:
                    apiURL = "API地址";
                    postBytes = System.Text.Encoding.Default.GetBytes(
                        "email=" + DataLogin.instance.CurAccount + "&userId=" + DataLogin.instance.GetUserID()
                        );
                    StartCoroutine(ConnectPost(webURL + apiURL, postBytes, 1));
                    break;
                case connectState.AddGold:
                    apiURL = "API地址";
                    dataJson["gold"] = DataLogin.instance.CurAddGold;
                    dataJson["userId"] = DataLogin.instance.GetUserID();
                    postBytes = System.Text.Encoding.Default.GetBytes(dataJson.ToJson());//把json格式的字符串转化成数组
                    StartCoroutine(ConnectPost(webURL + apiURL, postBytes, 0));
                    break;
                case connectState.phone:
                    apiURL = "/phone";
                    StartCoroutine(ConnectGet("http://www.hongyugege.com/game/user"+ apiURL+"?phone=15531554321" ));
                    break;
                case connectState.score:
                    apiURL = "/score";
                    StartCoroutine(ConnectGet("http://www.hongyugege.com/game/user" + apiURL + "?phone=15130286976&score=999"));
                    break;
                case connectState.login2:
                    apiURL = "/login";
                    StartCoroutine(ConnectGet("http://www.hongyugege.com/game/user" + apiURL + "?phone=15130286976&userName=test001"));
                    break;
                case connectState.users:
                    apiURL = "/users";
                    StartCoroutine(ConnectGet("http://www.hongyugege.com/game/user" + apiURL));
                    break;
                default:
                    IsBusy = false;
                    break;
            }            
        }
    }

    /// 
    /// POST方式连接
    /// 
    /// 
    /// 
    /// 
    IEnumerator ConnectPost(string url, byte[] postBytes,int headerType)
    {
        Utils.Log(url);
        UnityWebRequest request = new UnityWebRequest(url, "POST");//method传输方式,默认为Get;

        request.uploadHandler = new UploadHandlerRaw(postBytes);//实例化上传缓存器
        request.downloadHandler = new DownloadHandlerBuffer();//实例化下载存贮器
        request.SetRequestHeader("Content-Type", headerType == 0 ? "application/json" : "application/x-www-form-urlencoded");//更改内容类型,
        request.SetRequestHeader("appId", appId);
        yield return request.SendWebRequest();//发送请求

        Utils.Log("Status Code: " + request.responseCode);//获得返回值
        IsBusy = false;
        if (request.responseCode == 200)//检验是否成功
        {
            IsBusy = false;
            Utils.Log("connect success");
            string dataStr = request.downloadHandler.text;//打印获得值
            switch (currentState)
            {
                case connectState.Register:
                    DataHandleRegister(dataStr);
                    break;
                case connectState.Login:
                    DataHandleLogin(dataStr);
                    break;
                case connectState.ConsumeGold:
                    DataHandleConsumeGold(dataStr);
                    break;
                case connectState.ResetPassword:
                    DataHandleResetPassword(dataStr);
                    break;
                case connectState.RetrievePassword:
                    DataHandleRetrievePassword(dataStr);
                    break;
                case connectState.AddGold:
                    DataHandleAddGold(dataStr);
                    break;
                default:
                    break;
            }
        }
        else
        {
            Utils.Log("connect failed,error code is " + request.responseCode);
            ViewSystemTips.instance.show(DataTips.Net_Connect_Failed+"code:"+ request.responseCode);
            IsBusy = false;
            switch (currentState)
            {
                case connectState.Register:
                    DataLogin.instance.SetUserAccount("");
                    DataLogin.instance.SetUserPasswrod("");
                    DataLogin.instance.SetCode("");
                    break;
                case connectState.Login:
                    DataLogin.instance.SetUserAccount("");
                    DataLogin.instance.SetUserPasswrod("");
                    break;                
                default:
                    break;
            }
        }
    }

    /// 
    /// get方式进行连接
    /// 
    /// 
    /// 
    IEnumerator ConnectGet(string _url)
    {
        Utils.Log("url = "+_url);
        UnityWebRequest request = UnityWebRequest.Get(_url);
        request.SetRequestHeader("appId",appId);
        yield return request.SendWebRequest();
            if (request.responseCode == 200)
            {
                IsBusy = false;
                Utils.Log("connect success");                
                string dataStr = request.downloadHandler.text;
                switch (currentState)
                {
                    case connectState.GetCode:
                        DataHandleToken(dataStr);
                        break;
                    case connectState.GetGold:
                        DataHandleGold(dataStr);
                        break;
                case connectState.phone:
                    DataPhone(dataStr);
                    break;
                case connectState.score:
                    DataScore(dataStr);
                    break;
                case connectState.login2:
                    DataLogin2(dataStr);
                    break;
                case connectState.users:
                    DataUsers(dataStr);
                    break;
                default:
                        break;
                }
            }
            else
            {
                Utils.Log("connect failed,error code is " + request.responseCode);
                ViewSystemTips.instance.show(DataTips.Net_Connect_Failed+ "code is:"+request.responseCode);
                IsBusy = false;
            }
    }

    /// 
    /// 处理注册数据
    /// 
    private void DataHandleRegister(string _data)
    {
        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("register success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            JObject resultObj = JObject.Parse(resultStr);
            Utils.Log("account:" + resultObj["account"].ToString());
            Utils.Log("gold:" + resultObj["gold"].ToString());
            Utils.Log("token:" + resultObj["token"].ToString());
            Utils.Log("userId:" + resultObj["userId"].ToString());
            DataLogin.instance.SetUserAccount(resultObj["account"].ToString());
            DataLogin.instance.SetTokne(resultObj["token"].ToString());
            DataLogin.instance.SetUserID(resultObj["userId"].ToString());
            ViewSystemTips.instance.show(DataTips.Net_Register_Success);
            DataLogin.instance.SaveLocalUserData();
            EventManage.Instance.Event(EventName.Net_Register_Success, null);
        }
        else
        {
            Utils.Log("register failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);            
            ViewSystemTips.instance.show(messageStr);
        }
        
    }


    /// 
    /// 处理登陆数据
    /// 
    private void DataHandleLogin(string _data)
    {
        
        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("login success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            JObject resultObj = JObject.Parse(resultStr);
            Utils.Log("account:" + resultObj["account"].ToString());
            Utils.Log("gold:" + resultObj["gold"].ToString());
            Utils.Log("token:" + resultObj["token"].ToString());
            Utils.Log("userId:" + resultObj["userId"].ToString());
            DataLogin.instance.SetUserAccount(resultObj["account"].ToString());
            DataLogin.instance.SetTokne(resultObj["token"].ToString());
            DataLogin.instance.SetUserID(resultObj["userId"].ToString());

           int gold = int.Parse(resultObj["gold"].ToString());
            LocalData.GetInstance().SetCoinTotal(gold);
            //if (gold == 0)
            //{
            //    if (LocalData.GetInstance().GetGold() > 0)
            //    {
            //        DataLogin.instance.CurAddGold = LocalData.GetInstance().GetGold();
            //        Client(connectState.AddGold);
            //    }
            //}
            //else
            //{
            //    if (LocalData.GetInstance().GetGold() > gold)
            //    {
            //        DataLogin.instance.CurAddGold = LocalData.GetInstance().GetGold()- gold;
            //        Client(connectState.AddGold);
            //    }
            //    else
            //    {
            //        DataLogin.instance.CurConsumeGoldIndex = -1;
            //        DataLogin.instance.CurGoldConsumeNum = gold-LocalData.GetInstance().GetGold();
            //        Client(connectState.ConsumeGold);
            //    }
            //}   
            ViewSystemTips.instance.show(DataTips.Net_Login_Success);
            DataLogin.instance.SaveLocalUserData();
            LocalData.GetInstance().SaveLocalData();
            EventManage.Instance.Event(EventName.Net_Login_Success, null);

        }
        else
        {
            Utils.Log("login failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);
        } 
    }

    /// 
    /// 处理消耗金币数据
    /// 
    private void DataHandleConsumeGold(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("consume gold success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            
            //发送金币消耗成功事件,在注册位置进行本地数据修改
            EventManage.Instance.Event(EventName.Net_ConsumeGold_Success, null);
            Utils.Log("金币消耗成功,处理游戏逻辑"+ DataLogin.instance.CurConsumeGoldIndex);
        }
        else
        {
            Utils.Log("consume gold failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);
        }
    }
    

    /// 
    /// 处理修改密码数据
    /// 
    private void DataHandleResetPassword(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("reset password success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            
            EventManage.Instance.Event(EventName.Net_ResetPassword_Success, null);
            ViewSystemTips.instance.show(DataTips.Net_ResetPassword_Success);
        }
        else
        {
            Utils.Log("reset password failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);
        }
    }

    /// 
    /// 处理找回密码发送邮箱密码数据
    /// 
    private void DataHandleRetrievePassword(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("retrieve password success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            EventManage.Instance.Event(EventName.Net_RetrievePassword_Success, null);
            ViewSystemTips.instance.show(DataTips.Net_RetrievePassword_Success);
        }
        else
        {
            Utils.Log("retrieve password failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);
        }
    }

    /// 
    /// 处理找增加金币数据
    /// 
    private void DataHandleAddGold(string _data)
    {
        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("add gold success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            //EventManage.Instance.Event(EventName.Net_AddGold_Success, null);            
        }
        else
        {
            Utils.Log("retrieve password failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);

        }
    }

    /// 
    /// 处理获取验证码数据
    /// 
    private void DataHandleToken(string _data)
    {
        
        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("get token success");
            string codeStr = jsObj["result"].ToString();
            Utils.Log("code:" + codeStr);
            DataLogin.instance.SetCode(codeStr);
            EventManage.Instance.Event(EventName.Net_GetCode_Success, null);
        }
        else
        {
            Utils.Log("get token failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);
        }        
    }

    /// 
    /// 处理获取金币数据
    /// 
    private void DataHandleGold(string _data)
    {
        
        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        string statusStr = jsObj["status"].ToString();
        if (statusStr.Equals("success"))
        {
            Utils.Log("get gold success");
            string resultStr = jsObj["result"].ToString();
            Utils.Log("result:" + resultStr);
            JObject resultObj = JObject.Parse(resultStr);
            string goldStr = resultObj["gold"].ToString();
            Utils.Log("gold:" + goldStr);
            LocalData.GetInstance().SetCoinTotal(int.Parse(goldStr));
            EventManage.Instance.Event(EventName.Net_GetCode_Success,null);
        }
        else
        {
            Utils.Log("get gold failed");
            string messageStr = jsObj["message"].ToString();
            Utils.Log("message:" + messageStr);
            ViewSystemTips.instance.show(messageStr);
        }            
    }

    /// 
    /// 处理获取金币数据
    /// 
    private void DataPhone(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        //string statusStr = jsObj["status"].ToString();
        //if (statusStr.Equals("success"))
        //{
        //    Utils.Log("get gold success");
        //    string resultStr = jsObj["result"].ToString();
        //    Utils.Log("result:" + resultStr);
        //    JObject resultObj = JObject.Parse(resultStr);
        //    string goldStr = resultObj["gold"].ToString();
        //    Utils.Log("gold:" + goldStr);
        //    LocalData.GetInstance().SetCoinTotal(int.Parse(goldStr));
        //    EventManage.Instance.Event(EventName.Net_GetCode_Success, null);
        //}
        //else
        //{
        //    Utils.Log("get gold failed");
        //    string messageStr = jsObj["message"].ToString();
        //    Utils.Log("message:" + messageStr);
        //    ViewSystemTips.instance.show(messageStr);
        //}
    }
    /// 
    /// 处理获取金币数据
    /// 
    private void DataScore(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        //string statusStr = jsObj["status"].ToString();
        //if (statusStr.Equals("success"))
        //{
        //    Utils.Log("get gold success");
        //    string resultStr = jsObj["result"].ToString();
        //    Utils.Log("result:" + resultStr);
        //    JObject resultObj = JObject.Parse(resultStr);
        //    string goldStr = resultObj["gold"].ToString();
        //    Utils.Log("gold:" + goldStr);
        //    LocalData.GetInstance().SetCoinTotal(int.Parse(goldStr));
        //    EventManage.Instance.Event(EventName.Net_GetCode_Success, null);
        //}
        //else
        //{
        //    Utils.Log("get gold failed");
        //    string messageStr = jsObj["message"].ToString();
        //    Utils.Log("message:" + messageStr);
        //    ViewSystemTips.instance.show(messageStr);
        //}
    }
    /// 
    /// 处理获取金币数据
    /// 
    private void DataLogin2(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        //string statusStr = jsObj["status"].ToString();
        //if (statusStr.Equals("success"))
        //{
        //    Utils.Log("get gold success");
        //    string resultStr = jsObj["result"].ToString();
        //    Utils.Log("result:" + resultStr);
        //    JObject resultObj = JObject.Parse(resultStr);
        //    string goldStr = resultObj["gold"].ToString();
        //    Utils.Log("gold:" + goldStr);
        //    LocalData.GetInstance().SetCoinTotal(int.Parse(goldStr));
        //    EventManage.Instance.Event(EventName.Net_GetCode_Success, null);
        //}
        //else
        //{
        //    Utils.Log("get gold failed");
        //    string messageStr = jsObj["message"].ToString();
        //    Utils.Log("message:" + messageStr);
        //    ViewSystemTips.instance.show(messageStr);
        //}
    }

    private void DataUsers(string _data)
    {

        Utils.Log("data:" + _data);
        JObject jsObj = JObject.Parse(_data);
        //string statusStr = jsObj["status"].ToString();
        //if (statusStr.Equals("success"))
        //{
        //    Utils.Log("get gold success");
        //    string resultStr = jsObj["result"].ToString();
        //    Utils.Log("result:" + resultStr);
        //    JObject resultObj = JObject.Parse(resultStr);
        //    string goldStr = resultObj["gold"].ToString();
        //    Utils.Log("gold:" + goldStr);
        //    LocalData.GetInstance().SetCoinTotal(int.Parse(goldStr));
        //    EventManage.Instance.Event(EventName.Net_GetCode_Success, null);
        //}
        //else
        //{
        //    Utils.Log("get gold failed");
        //    string messageStr = jsObj["message"].ToString();
        //    Utils.Log("message:" + messageStr);
        //    ViewSystemTips.instance.show(messageStr);
        //}
    }
}

类:

你可能感兴趣的:(Unity3D,unity,http,linq)