注意事项:
关于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 ==){
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 > )
{
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, , 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, , 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-,);
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 (, );
sb.Remove (sb.Length - , );
string t = "" + sb;
string[] temp = Regex.Split (t, ",", RegexOptions.IgnoreCase); for (int i = ; i < temp.Length; i++) {
temp[i] = Regex.Replace (temp [i], "\"","", RegexOptions.IgnoreCase);
string[] splits = Regex.Split (temp [i],":", RegexOptions.IgnoreCase);
result.Add (splits [].ToString(), splits [].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[];
rlen = ;
_ms = new MemoryStream();
while ((rlen = _stream.Read(buff, , )) > )
{
_ms.Write(buff, , rlen);
}
buff = _ms.ToArray();
_ms.Close();
_ms.Dispose();
return buff;
}
return null;
}
}
}

Unity的弱联网Json数据传输的更多相关文章

  1. Java游戏服务器成长之路——弱联网游戏篇(源码分析)

    前言 前段时间由于公司的一款弱联网游戏急着上线,没能及时分享,现在基本做的差不多,剩下的就是测试阶段了(本来说元旦来分享一下服务器技术的).公司的这款游戏已经上线一年多了,在我来之前一直都是单机版本, ...

  2. 【Cocos2d-Js基础教学(6)网络层(弱联网)的封装及使用】

    谈到联网,在游戏中也是非常核心的模块,在官方Js-test中我们可以找到联网部分 的NetworkTest文件下有两个类 SocketIOTest.js(Socket 类) WebSocketTest ...

  3. 单机 &amp; 弱联网手游 防破解、金币改动 简单措施

    手游经常使用破解方法 对于一个弱联网或者单机游戏,能够从下面方面去破解: 1.找得到存档文件的,直接破解改动存档文件. 2.找不到存档文件,就在游戏执行时借助一些软件来改动数值,比方用各种改动器手游助 ...

  4. 【Cocos2d-x游戏开发】Cocos2d-x中的弱联网技术

    在上一篇博客中,我们一起学习了如何在Cocos2d-x中存储数据和读取信息,本篇博客我们将一起讨论和数据存储同样重要的联网技术. 一.弱联网技术介绍 在网络游戏中许多重要的功能都需要网络连接,而根据需 ...

  5. 5.QT中关于HTTPClient相关的操作,Json数据传输

     新建项目T12HttpClient T12HttpClient.pro SOURCES += \ main.cpp QT += network CONFIG += C++11 main.cpp ...

  6. Unity判断用户联网状态,WiFi/移动网络/无网络

    Unity判断用户联网状态 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分享. ...

  7. Unity游戏数据用Json保存

    (一)关于路径 unity有几个关键的路径 (1).Application.dataPath 只读路径,就是工作目录的Assets路径 (2).Application.streamingAssetsP ...

  8. unity 通过JsonUtility实现json数据的本地保存和读取

    本文主要讲解json数据在本地的保存和读取,使用的是unity5之后提供的JsonUtility工具. 一.关于json数据的保存 在实际开发中,有时候可能涉及到大量数据保存到本地,以便于下次客户端的 ...

  9. 【一天一个小知识10/20】Unity通过www获取json文本信息。

    前提:领导要我在unity获取局域网服务器的文本信息.给了一个json的网络文本让我测试.我对于json以及服务器比较陌生.就直接去网上找相关的资料. 以下是自己测试的代码,没问题. 测试的网络jso ...

随机推荐

  1. BFS(三):双向广度优先搜索

    所谓双向广度搜索指的是搜索沿两个方向同时进行:(1)正向搜索:从初始结点向目标结点方向搜索:(2)逆向搜索:从目标结点向初始结点方向搜索:当两个方向的搜索生成同一子结点时终止此搜索过程. 广度双向搜索 ...

  2. easyui close的最大化的dialog 切换 tab 再次出现

    今天发现一个神奇的bug,easyui中的dialog在经历了d.panel('close');之后,当前的tab仍然未关闭,切换了另一tab,然后回去刚才的tab,发现已经close的dialog又 ...

  3. django基础知识之Ajax:

    使用Ajax 使用视图通过上下文向模板中传递数据,需要先加载完成模板的静态页面,再执行模型代码,生成最张的html,返回给浏览器,这个过程将页面与数据集成到了一起,扩展性差 改进方案:通过ajax的方 ...

  4. Java 集合类Hashmap

    一.HashMap 简介 HashMap在程序员的开发过程中是一个十分常用的集合类,它是一个以键值对形式存在的集合类, 在开发中我们可以利用的它的一个key存在即替换的特性,实现一个更新的去重的操作. ...

  5. 网络下载器 Pan Download v2.0.5 Lite 绿色便携版

    下载地址:点我 基本介绍 PanDownload最新版是一款能够快速下载百度网盘内资源的强大工具.PanDownload最新版能够无限速高速下载,满速下载百度云盘里的各种资源.而且PanDownloa ...

  6. 剑指offer第二版-7.重建二叉树

    描述:输入某二叉树的前序遍历和中序遍历结果,重建该二叉树.假设前序遍历或中序遍历的结果中无重复的数字. 思路:前序遍历的第一个元素为根节点的值,据此将中序遍历数组拆分为左子树+root+右子树,前序遍 ...

  7. Codeforces比赛注意事项(英语比较好,能翻译题目的可以跳过此文章)

    由题目可知,这篇文章是讲翻译文章的. 当然不是教英语啦 其实cf的比赛对于本蒟蒻最大的挑战就是翻译题目啦 所以我比赛时只能靠各种翻译器去无耻地翻译,然后读中文. 目前较好的翻译器有:百度,谷歌,有道. ...

  8. asp.net core 系列之静态文件

    这篇讲解asp.net core中的静态文件(大致翻译于官网). 静态文件,例如HTML,CSS, images和JavaScript. 要想直接被客户端访问,需要做一些配置. 一.Serve sta ...

  9. 【数据库】postgresql数据库创建自增序列id的注意事项

    1.创建一张表 CREATE TABLE "public"."tt" ( "name" varchar(128), "status ...

  10. linux初学者-数据库管理MariaDB篇

    linux初学者-数据库管理MariaDB篇 MariaDB是一种数据库管理系统,是MySQL的一个分支,但是比MySQL更加优秀,可以说是MySQL的替代品.MariaDB使用的是SQL语句.下文将 ...