这个例子是向后台发送卡号机器码以及mac地址获取地磅的设置信息
1.请求数据时需要发送的字段
LoadometerSettingByAccessCardPacket.cs
nuget引入
Newtonsoft.Json.dll
public class LoadometerSettingByAccessCardPacket { [Newtonsoft.Json.JsonIgnore] public string cmd { get; set;} public LoadometerSettingByAccessCardPacket() { cmd = "LoadometerSettingByAccessCard"; } /// <summary> /// 门禁卡编号 /// </summary> public string accesscardnum { get; set; } /// <summary> /// 机器码 /// </summary> public string mcode { get; set; } /// <summary> ///Mac地址 /// </summary> public string macaddress { get; set; } }
2.发送请求类
Packet.cs
public class Packet {/// <summary> /// 发送请求类 /// </summary> private string responseJsonStr; // request json & response json 字符串 private string requestJsonStr; private byte[] contentByte; // request byte[] & response byte[] /// <summary> /// 发送数据 /// </summary> public string data { get; set; } /// <summary> /// 命令 /// </summary> public string cmd { get; set; } public string RequestData(LoadometerSettingByAccessCardPacket pacSend) { requestJsonStr = GetJson(pacSend); contentByte = System.Text.Encoding.UTF8.GetBytes(requestJsonStr); // 压缩contentByte contentByte = ZipHelper.Compress(contentByte); // 加密contentByte contentByte = DESHelper.Encrypt(contentByte); contentByte = HttpRequest.PostRequest(contentByte); //Send packet // 解密contentByte contentByte = DESHelper.Decrypt(contentByte); // 解压contentByte contentByte = ZipHelper.Decompress(contentByte); responseJsonStr = System.Text.Encoding.UTF8.GetString(contentByte); return responseJsonStr; } /// 获取数据发送JSON /// </summary> /// <param name="obj"></param> /// <returns></returns> public string GetJson(LoadometerSettingByAccessCardPacket obj) { try { cmd = obj.cmd; data = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { //ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() ContractResolver = new UnderlineSplitContractResolver() }); return JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new UnderlineSplitContractResolver() }); } catch { return ""; } } }
3.压缩类
ZipHelper.cs
public class ZipHelper { /// <summary> /// 压缩byte[] /// </summary> /// <param name="data"></param> /// <returns>返回压缩后的byte[]</returns> public static byte[] Compress(byte[] data) { if (data == null) { return null; } using (MemoryStream ms = new MemoryStream()) { GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true); compressedzipStream.Write(data, 0, data.Length); compressedzipStream.Close(); return ms.ToArray(); } } /// <summary> /// 压缩字符串 /// </summary> /// <param name="str"></param> /// <returns>压缩后的字符串</returns> public static string Compress(string str) { if (string.IsNullOrEmpty(str)) { return ""; } byte[] data = System.Text.Encoding.UTF8.GetBytes(str); return Encoding.UTF8.GetString(Compress(data)); } /// <summary> /// 解压byte[] /// </summary> /// <param name="zippedData"></param> /// <returns>解压后的byte[]</returns> public static byte[] Decompress(byte[] data) { if (data == null) { return null; } using (MemoryStream outBuffer = new MemoryStream()) { MemoryStream ms = new MemoryStream(data); GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress); byte[] block = new byte[1024]; while (true) { int bytesRead = compressedzipStream.Read(block, 0, block.Length); if (bytesRead <= 0) break; else outBuffer.Write(block, 0, bytesRead); } compressedzipStream.Close(); ms.Close(); return outBuffer.ToArray(); } } /// <summary> /// 解压字符串 /// </summary> /// <param name="str"></param> /// <returns>解压后的字符串</returns> public static string Decompress(string str) { if (string.IsNullOrEmpty(str)) { return ""; } else { byte[] data = Encoding.UTF8.GetBytes(str); return Encoding.UTF8.GetString(Decompress(data)); } } }
4.加密解密类
DESHelper.cs
public class DESHelper { #region 加密 /// <summary> 加密字符串 /// </summary> /// <param name="str">要加密的字符串</param> /// <returns>加密后的字符串</returns> public static string Encrypt(string str) { if (string.IsNullOrEmpty(str)) { return ""; } byte[] data = Encoding.UTF8.GetBytes(str); return Encoding.UTF8.GetString(Encrypt(data)); } /// <summary> 加密byte[] /// </summary> /// <param name="str">要加密的byte[]</param> /// <returns>加密后的byte[]</returns> public static byte[] Encrypt(byte[] data) { if (data == null) { return null; } try { using (MemoryStream MStream = new MemoryStream())//实例化内存流对象 { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //实例化加/解密类对象 byte[] key = Encoding.UTF8.GetBytes("STEEL021"); //定义字节数组,用来存储密钥 //使用内存流实例化加密流对象 CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); //向加密流中写入数据 CStream.FlushFinalBlock();//释放加密流 CStream.Close(); return MStream.ToArray(); } } catch { return null; } } #endregion #region 解密 /// <summary> /// 解密字符串 /// </summary> /// <param name="str">要解密的字符串</param> /// <returns>解密后的字符串</returns> public static string Decrypt(string str) { if (string.IsNullOrEmpty(str)) { return ""; } byte[] data = Encoding.UTF8.GetBytes(str);//定义字节数组,用来存储要解密的字符串 return Encoding.UTF8.GetString(Decrypt(data)); } /// <summary> /// 解密byte[] /// </summary> /// <param name="str">要解密的byte[] </param> /// <returns>解密后的byte[] </returns> public static byte[] Decrypt(byte[] data) { if (data == null) { return null; } try { using (MemoryStream MStream = new MemoryStream())//实例化内存流对象 { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //实例化加/解密类对象 byte[] key = Encoding.UTF8.GetBytes("STEEL021"); //定义字节数组,用来存储密钥 //使用内存流实例化解密流对象 CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); //向解密流中写入数据 CStream.FlushFinalBlock(); //释放解密流 CStream.Close(); return MStream.ToArray(); } } catch { return null; } } #endregion }
5.发送Http请求类
HttpRequest.cs
public class HttpRequest { /// <summary> /// Post方式发送Http请求 /// </summary> /// <param name="packetData">数据</param> /// <param name="mes">异常信息</param> /// <returns></returns> public static byte[] PostRequest(byte[] packetData) { try { var listByte = new List<byte>(); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://180.166.99.4:20361/restapi/atm"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = packetData.Length; req.Timeout = 120000; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(packetData, 0, packetData.Length); } using (HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse()) { BinaryReader reader = new BinaryReader(myResponse.GetResponseStream()); byte[] buffer = new byte[1024]; while (true) { int count = reader.Read(buffer, 0, buffer.Length); if (count <= 0) break; listByte.AddRange(buffer.Take(count)); } } return listByte.ToArray(); } catch (Exception e) { return null; } } }
6.UnderlineSplitContractResolver.cs
public class UnderlineSplitContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return CamelCaseToUnderlineSplit(propertyName); } private string CamelCaseToUnderlineSplit(string name) { return name.ToLower(); } }
7.从后台返回的设置信息
SettingPC.cs
public class SettingPC { //地磅名 public string loadometerName { get; set; } //mac地址 public string loadometerMacAddress { get; set; } //仓库 public string warehouse { get; set; } //仓库id public string warehouseId { get; set; } //电话号 public string phone { get; set; } //晚上音量 public string volumeNight { get; set; } //白天音量 public string volumeDay { get; set; } public string msg { get; set; } public string status { get; set; } public string data { get; set; }//取出json中的data,重新转成json再解析 }
8.发送请求,和后台进行数据交互,获取后台返回数据
引用System.Web.Extensions.dll
LoadometerSettingByAccessCardPacket rcpacket = new LoadometerSettingByAccessCardPacket(); rcpacket.accesscardnum = "01181630630533377565"; string license = Computer.Instance().GetATMAll();//获取机器码 rcpacket.mcode = license; rcpacket.macaddress = "089798FC1748"; Packet instance = new Packet(); var responsejson= instance.RequestData(rcpacket); JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue }; //实例化一个能够序列化数据的类 SettingPC setting = js.Deserialize<SettingPC>(responsejson); //将json数据转化为对象类型并赋值给setting string data= setting.data;//将data字符串取出来转成json重新解析 var msg=setting.msg; var status = setting.status; if (status!= "1") { MessageBox.Show(msg); return; } JObject redata = (JObject)JsonConvert.DeserializeObject(data); SettingPC settingdata = js.Deserialize<SettingPC>(redata.ToString()); string name = settingdata.warehouse; MessageBox.Show(name);
注:前面七项都是为发送请求写好的类,第八项解析俩次是因为获取的json嵌入了俩层。