Unity使用UnityWebRequest进行POST/GET进行网络请求实例,已测试通过 可直接使用
  MaGrnHO9I9EL 2023年11月02日 120 0
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;

/// <summary>
/// 网络连接类
/// </summary>
public class NetClient : MonoBehaviour
{
    public static NetClient instance;
    private void Awake()
    {
        instance = this;
    }

    private string webURL = "服务器地址";
    private string apiURL = "";
    private string appId = "003113";

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

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

    #region 属性

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

    #endregion

 
    /// <summary>
    /// 开始连接服务器
    /// </summary>
    /// <param name="_state"></param>
    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/client/v1/user/register";
                    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/client/v1/user/login";
                    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/client/v1/user/getCode";
                    StartCoroutine(ConnectGet(webURL + apiURL + "?account=" + DataLogin.instance.GetUserAccount()));
                    break;
                case connectState.GetGold:
                    apiURL = "/api/client/v1/user/account";
                    StartCoroutine(ConnectGet(webURL+apiURL+ "?userId="+DataLogin.instance.GetUserID()));
                    break;
                case connectState.ConsumeGold:
                    apiURL = "/api/client/v1/user/consumeGold";
                    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/client/v1/user/resetPassword";
                    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/client/v1/user/retrievePassword";
                    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/client/v1/user/addGold";
                    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;
                default:
                    IsBusy = false;
                    break;
            }            
        }
    }

    /// <summary>
    /// POST方式连接
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postBytes"></param>
    /// <returns></returns>
    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;
            }
        }
    }

    /// <summary>
    /// get方式进行连接
    /// </summary>
    /// <param name="_url"></param>
    /// <returns></returns>
    IEnumerator ConnectGet(string _url)
    {
        Utils.Log(_url);
        UnityWebRequest request = UnityWebRequest.Get(_url);
        request.SetRequestHeader("appId", appId);
        yield return request.SendWebRequest();
        //if (request.isError)
        //{
        //    IsBusy = false;
        //    Utils.Log("connect failed,error code is " + request.responseCode);
        //    ViewSystemTips.instance.show("Server connection failed");
        //}
        //else
        //{
            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;
                    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;
            }
        //}
    }

    /// <summary>
    /// 处理注册数据
    /// </summary>
    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);
        }
        
    }


    /// <summary>
    /// 处理登陆数据
    /// </summary>
    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);
        } 
    }

    /// <summary>
    /// 处理消耗金币数据
    /// </summary>
    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);
        }
    }
    

    /// <summary>
    /// 处理修改密码数据
    /// </summary>
    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);
        }
    }

    /// <summary>
    /// 处理找回密码发送邮箱密码数据
    /// </summary>
    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);
        }
    }

    /// <summary>
    /// 处理找增加金币数据
    /// </summary>
    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);

        }
    }

    /// <summary>
    /// 处理获取验证码数据
    /// </summary>
    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);
        }        
    }

    /// <summary>
    /// 处理获取金币数据
    /// </summary>
    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);
        }            
    }
}
///*
// * url:为请求地址
// * postData:请求内容例如:"key1=value1&key2=value2&key3=value3"
// */
//void PostUrl(string url, string postData)
//{
//    IsBusy = false;
//    Utils.Log(url + "," + postData);
//    string result = "";
//    try
//    {
//        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//        req.Method = "POST";
//        req.ContentType = "application/x-www-form-urlencoded";
//        req.Timeout = 8000;//请求超时时间
//        byte[] data = Encoding.UTF8.GetBytes(postData);
//        req.ContentLength = data.Length;
//        using (Stream reqStream = req.GetRequestStream())
//        {
//            reqStream.Write(data, 0, data.Length);

//            reqStream.Close();
//        }
//        Utils.Log("HttpWebRequest send success");
//        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
//        Stream stream = resp.GetResponseStream();
//        //获取响应内容
//        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
//        {
//            result = reader.ReadToEnd();
//            Utils.Log("result=====================" + result);
//            DataHandleRetrievePassword(result);
//        }
//    }
//    catch (Exception e)
//    {
//        Utils.Log("e=====================" + e.Message);

//    }
//}

json解析用到了LitJson.dllNewtonsoft.Json.dll

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论