1. 程式人生 > >Unity的弱聯網Json資料傳輸

Unity的弱聯網Json資料傳輸

注意事項: 關於dictionary轉json的工程中遇到一點問題:要手動新增雙引號。 關於json轉dictionary:同樣需要手動去掉雙引號,否則新增到dictionary中的字串會帶有雙引號。打log的時候字串輸出本身是沒有雙引號的。   返回Dictionary資料,程式碼都很簡單,json的處理,當然也可以用其他json外掛Litjson等,直接上程式碼。   呼叫程式碼:
  void Start () {
        Thread t = new Thread (Check);    // No need to explicitly use ThreadStart
        t.Start();
 
    }
    static string TestServer = "http://192.168.1.105:8080/cross";
    static void Check() {
        HttpClients httpClient = new HttpClients();
        Dictionary<string, string
> data = new Dictionary<string, string>(); if(result==null){ result = new Dictionary<string, string>(); }else{ result.Clear(); } data.Add("appName","cutit"); data.Add("platform","android"); data.Add("language","chinese
"); data.Add("channel","offical"); ResultResponse resultResponse = httpClient.OpenPostUrl(TestServer,null,data); string resultString = resultResponse.GetContent().ToString(); Dictionary<string, string>m = httpClient.JsonToDict(resultString); int resultCode = int
.Parse(m["resultCode"]); if(resultCode ==0){ string adState = "" + m["adState"]; string isShowLogoText = "" + m["key1"]; Debug.Log("steve:" + adState + ":" + isShowLogoText); if(adState == "OFF"){ } if(isShowLogoText == "ON"){ } } }
以下是 HttpClient 和 ResultResponse
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
using System.Text.RegularExpressions;


namespace HttpClient
{
 
    /// <summary>
    /// 通過Http協議訪問Web
    /// </summary>
    public class HttpClients
    {
        #region Cookie集合
        /// <summary>
        /// Cookie集合
        /// </summary>
        private CookieContainer cookies;
        #endregion
 
        #region Http user-agent標頭值
        /// <summary>
        /// Http user-agent標頭值
        /// </summary>
        public string UserAgent { get; set; }
        #endregion
 
        #region HttpClient建構函式
        public HttpClients()
        {
            this.cookies = new CookieContainer();
        }
        #endregion 
 
        #region 獲取HttpClient的Cookie集合
        /// <summary>
        /// 獲取HttpClient的Cookie集合
        /// </summary>
        /// <returns></returns>
        public CookieContainer GetCookieContainer()
        {
            return this.cookies;
        }
        #endregion
 
        #region 設定HttpClient的Cookie集合
        /// <summary>
        /// 設定HttpClient的Cookie集合
        /// </summary>
        /// <param name="_cookie">Cookie集合物件</param>
        /// <returns>True設定成功 False設定失敗</returns>
        public bool SetCookieContainer(CookieContainer _cookie)
        {
            if (_cookie != null)
            {
                this.cookies = _cookie;
                return true;
            }
            return false;
        }
        #endregion
 
        #region 以GET方式開啟一個Http連線
        /// <summary>
        /// 以GET方式開啟一個Http連線
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <returns></returns>
        public ResultResponse OpenGetUrl(string url, Dictionary<string, string> headers)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClients.ConnectionType.GET;
            request.KeepAlive = true;
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            return new ResultResponse(response);
        }
        #endregion
 
        #region 以GET方式開啟一個Http連線,302自定義處理行為
        /// <summary>
        /// 以GET方式開啟一個Http連線,302自定義處理行為
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <param name="action">302跳轉處理</param>
        /// <returns></returns>
        public ResultResponse OpenGetUrlRedirect(string url, Dictionary<string, string> headers,HttpClients.RedirectAction action)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClients.ConnectionType.GET;
            request.KeepAlive = true;
            request.AllowAutoRedirect = false; //302不採用預設行為處理
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            ResultResponse result=new ResultResponse(response);
            if (response.StatusCode == HttpStatusCode.Found)
            {
                bool ret = true;
                if (action != null)
                {
                    ret = action(result);
                }
                string locationurl = response.Headers["Location"];
                if (ret == true)
                {
                    return this.OpenGetUrlRedirect(locationurl, null, action);
                }
                return result;
            }
            return result;
        }
        #endregion
 
        #region Http 302跳轉處理
        /// <summary>
        /// Http 302跳轉處理
        /// </summary>
        /// <param name="result">響應物件</param>
        /// <returns>False 不繼續跳轉 True繼續跳轉</returns>
        public delegate bool RedirectAction(ResultResponse result);
        #endregion
 
        #region 將Http標頭值新增到Request物件中
        /// <summary>
        /// 將Http標頭值新增到Request物件中
        /// </summary>
        /// <param name="headers"></param>
        private void FillHeaders(HttpWebRequest request,Dictionary<string, string> headers)
        {
            if (headers != null && headers.Count > 0)
            {
                Dictionary<string, string>.Enumerator em = headers.GetEnumerator();
                while (em.MoveNext())
                {
                    request.Headers.Add(em.Current.Key, em.Current.Value);
                }
            }
        }
        #endregion
 
        #region 以POST方式開啟一個Http連線
        /// <summary>
        /// 以POST方式開啟一個Http連線
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <param name="data">傳送的資料</param>
        /// <returns></returns>
        public ResultResponse OpenPostUrl(string url,Dictionary<string,string> headers,Dictionary<string,string> data)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClients.ConnectionType.POST;
            request.KeepAlive = true;
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            byte[] buff = DictToBytes(data);
            request.GetRequestStream().Write(buff, 0, buff.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            return new ResultResponse(response);
        }
        #endregion
 
        #region 以POST方式開啟一個Http連線,302自定義處理行為
        /// <summary>
        /// 以POST方式開啟一個Http連線,302自定義處理行為
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <param name="data">傳送的資料</param>
        /// <param name="action">302自定義處理</param>
        /// <returns></returns>
        public ResultResponse OpenPostUrlRedirect(string url, Dictionary<string, string> headers, Dictionary<string, string> data,HttpClients.RedirectAction action)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClients.ConnectionType.POST;
            request.KeepAlive = true;
            request.AllowAutoRedirect = false;
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            byte[] buff = DictToBytes(data);
            request.GetRequestStream().Write(buff, 0, buff.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            ResultResponse result = new ResultResponse(response);
 
            if (response.StatusCode == HttpStatusCode.Found)
            {
                bool ret = true;
                if (action != null)
                {
                    ret = action(result);
                }
                string locationurl = response.Headers["Location"];
                return result;
            }
            return result;
        }
        #endregion
 
        #region 將字典的key和value拼接成http引數
        /// <summary>
        /// 將字典的key和value拼接成http引數
        /// </summary>
        /// <param name="dic">引數</param>
        /// <returns></returns>
        private byte[] DictToBytes(Dictionary<string, string> dic)
        {
            StringBuilder sb = null;
            if (dic != null)
            {
                Dictionary<string,string>.Enumerator em= dic.GetEnumerator();
                sb = new StringBuilder();
                sb.Append("{");
                while (em.MoveNext())
                {
                    sb.Append(String.Format("{0}:{1};", '"'+ em.Current.Key + '"', '"' + em.Current.Value + '"'));
                }
                sb.Remove (sb.Length-1,1);
                sb.Append("}");
                return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
            }
            return null;
        }

        public Dictionary<string, string> JsonToDict(string json)
        {
            StringBuilder sb = new StringBuilder(json);
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (json != null && json != "") {
                sb.Remove (0, 1);
                sb.Remove (sb.Length - 1, 1);
                string t = "" + sb;
                string[] temp = Regex.Split (t, ",", RegexOptions.IgnoreCase);

                for (int i = 0; i < temp.Length; i++) {    
                    temp[i] = Regex.Replace (temp [i], "\"","", RegexOptions.IgnoreCase);
                    string[] splits = Regex.Split (temp [i],":", RegexOptions.IgnoreCase);
                    result.Add (splits [0].ToString(), splits [1].ToString());
                }

                return result;
            }

            return null;
        }

        #endregion
 
        #region HttpClient開啟連線的方式
        /// <summary>
        /// HttpClient開啟連線的方式
        /// </summary>
        public static class ConnectionType
        {
            public static string GET { get { return "GET"; } }
            public static string POST { get { return "POST"; } }
        }
        #endregion
 
 
 
 
    }
}

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
 
namespace HttpClient
{
 
    /// <summary>
    ///包含伺服器響應資料的物件
    /// </summary>
    public class ResultResponse
    {
        #region HttpWebResponse物件
        /// <summary>
        /// HttpWebResponse物件
        /// </summary>
        private HttpWebResponse m_response;
        #endregion
 
        #region 建立一個HttpWebResponse物件
        /// <summary>
        /// 建立一個HttpWebResponse物件
        /// </summary>
        /// <param name="_response">HttpWebResponse</param>
        public ResultResponse(HttpWebResponse _response)
        {
            this.m_response = _response;
        }
        #endregion
 
        #region 獲取響應內容的二進位制流
        /// <summary>
        /// 獲取響應內容的二進位制流 
        /// </summary>
        /// <returns></returns>
        public Stream GetResponseStream()
        {
            if (this.m_response != null)
            {
                return this.m_response.GetResponseStream();
            }
            return null;
        }
        #endregion
 
        #region Http版本
        /// <summary>
        /// Http版本
        /// </summary>
        public string ProtocolVersion { get { return this.m_response != null ? this.m_response.ProtocolVersion.ToString() : ""; } }
        #endregion
        /// <summary>
        /// 響應方法
        /// </summary>
        public string Method { get { return this.m_response != null ? this.m_response.Method : ""; } }
        /// <summary>
        /// Http狀態碼
        /// </summary>
        public string StatusCode { get { return this.m_response != null ? this.m_response.StatusCode.ToString() : ""; } }
        /// <summary>
        /// Http響應頭
        /// </summary>
        public WebHeaderCollection Headers { get { return this.m_response != null ? this.m_response.Headers : null;} }
 
        /// <summary>
        /// 響應流的字元編碼
        /// </summary>
        /// <returns></returns>
        public Encoding getResponseEncoding()
        {
            if (this.m_response != null)
            {
                return Encoding.GetEncoding(this.m_response.ContentEncoding);
            }
            return null;
        }
 
        /// <summary>
        /// 獲取響應內容的字串
        /// </summary>
        /// <param name="encoding">字串編碼(預設utf8)</param>
        /// <returns></returns>
        public string GetContent(string encoding="utf-8")
        {
            return System.Text.Encoding.GetEncoding(encoding).GetString(this.StreamtoBytes(this.GetResponseStream()));

//            return System.Text.Encoding.GetEncoding(encoding).GetString(this.StreamtoBytes(this.GetResponseStream()));
        }
 
        /// <summary>
        /// 獲取原始的HttpWebResponse
        /// </summary>
        /// <returns></returns>
        public HttpWebResponse GetRawResponse()
        {
            return this.m_response;
        }
 
        /// <summary>
        /// 二進位制流轉換成位元組陣列
        /// </summary>
        /// <param name="_stream"></param>
        /// <returns></returns>
        private byte[] StreamtoBytes(Stream _stream)
        {
            byte[] buff;
            int rlen;
            MemoryStream _ms;
            if (_stream != null)
            {
                buff = new byte[1024];
                rlen = 0;
                _ms = new MemoryStream();
                while ((rlen = _stream.Read(buff, 0, 1024)) > 0)
                {
                    _ms.Write(buff, 0, rlen);
                }
                buff = _ms.ToArray();
                _ms.Close();
                _ms.Dispose();
                return buff;
            }
            return null;
        }
    }
}