C# Deflate 压缩与解压缩
2015-07-01 11:36
573 查看
//web Api
[DeflateCompression]
[HttpPost]
public HttpResponseMessage DeflateTest()
{
string httpRequestMessage = string.Format("{{\"status\":\"{0}\",\"message\":\"{1}\",\"userInfo\":{2}}}", "12", "Deflate压缩POST测试!", "[]");
return new HttpResponseMessage { Content = new StringContent(httpRequestMessage) };
}
//过滤器,写在web Api的类库里
public class DeflateCompressionAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actContext)
{
var content = actContext.Response.Content;
var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
var zlibbedContent = bytes == null ? new byte[0] :
CompressionHelper.DeflateByte(bytes);
actContext.Response.Content = new ByteArrayContent(zlibbedContent);
actContext.Response.Content.Headers.Remove("Content-Type");
actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
//actContext.Response.Content.Headers.Add("Content-Type", "application/json");
actContext.Response.Content.Headers.Add("Content-Type", "application/json;charset=utf-8");
base.OnActionExecuted(actContext);
}
}
public class CompressionHelper
{
public static byte[] DeflateByte(byte[] str)
{
if (str == null)
{
return null;
}
using (var output = new MemoryStream())
{
using (
var compressor = new Ionic.Zlib.DeflateStream(
output, Ionic.Zlib.CompressionMode.Compress,
Ionic.Zlib.CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
}
return output.ToArray();
}
}
public static byte[] GZipByte(byte[] str)
{
if (str == null)
{
return null;
}
using (var output = new MemoryStream())
{
using (
var compressor = new Ionic.Zlib.GZipStream(
output, Ionic.Zlib.CompressionMode.Compress,
Ionic.Zlib.CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
}
return output.ToArray();
}
}
//请求的单元测试
[TestMethod]
public void DeflateTest()
{
string html = string.Empty;
string postUrl = "http://localhost:8087/api/Contacts/DeflateTest";
string paramData = "userId=jlk456j5";
Encoding dataEncode = Encoding.UTF8;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
webReq.ContentLength = byteArray.Length;
//webReq.Headers["userId"] = DESHelper.Encrypt("1382888655");
//webReq.Headers["userPwd"] = DESHelper.Encrypt("123456789");
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
////0
////StreamReader sr = new StreamReader(response.GetResponseStream());
////html = sr.ReadToEnd();
////sr.Close();
//using (var s = response.GetResponseStream())
//{
// Encoding encode = Encoding.GetEncoding("utf-8");
// Byte[] read = new Byte[512];
// int bytes = s.Read(read, 0, 512);
// while (bytes > 0)
// {
// html += encode.GetString(read, 0, bytes);
// bytes = s.Read(read, 0, 512);
// }
//}
//2
Stream zipstream = response.GetResponseStream();
byte[] zipByte = ToByteArray(zipstream);
html = DeflateDecompress(zipByte);
response.Close();
newStream.Close();
}
catch (Exception ex)
{
string tt = "";
}
string twt = html;
//html = DESHelper.DesDecrypt(html);
}
private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
private string DeflateDecompress(byte[] buffer)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
ms.Write(buffer, 0, buffer.Length);
ms.Position = 0;
//using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
//{
// stream.Flush();
// int nSize = 16 * 1024 + 256; //假设字符串不会超过16K
// byte[] decompr
4000
essBuffer = new byte[nSize];
// int nSizeIncept = stream.Read(decompressBuffer, 0, nSize);
// stream.Close();
// return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept); //转换为普通的字符串
//}
using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
{
stream.Flush();
byte[] decompressBuffer = ToByteArray(stream);
int nSizeIncept = decompressBuffer.Length;
stream.Close();
return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept); //转换为普通的字符串
}
}
}
[DeflateCompression]
[HttpPost]
public HttpResponseMessage DeflateTest()
{
string httpRequestMessage = string.Format("{{\"status\":\"{0}\",\"message\":\"{1}\",\"userInfo\":{2}}}", "12", "Deflate压缩POST测试!", "[]");
return new HttpResponseMessage { Content = new StringContent(httpRequestMessage) };
}
//过滤器,写在web Api的类库里
public class DeflateCompressionAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actContext)
{
var content = actContext.Response.Content;
var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
var zlibbedContent = bytes == null ? new byte[0] :
CompressionHelper.DeflateByte(bytes);
actContext.Response.Content = new ByteArrayContent(zlibbedContent);
actContext.Response.Content.Headers.Remove("Content-Type");
actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
//actContext.Response.Content.Headers.Add("Content-Type", "application/json");
actContext.Response.Content.Headers.Add("Content-Type", "application/json;charset=utf-8");
base.OnActionExecuted(actContext);
}
}
public class CompressionHelper
{
public static byte[] DeflateByte(byte[] str)
{
if (str == null)
{
return null;
}
using (var output = new MemoryStream())
{
using (
var compressor = new Ionic.Zlib.DeflateStream(
output, Ionic.Zlib.CompressionMode.Compress,
Ionic.Zlib.CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
}
return output.ToArray();
}
}
public static byte[] GZipByte(byte[] str)
{
if (str == null)
{
return null;
}
using (var output = new MemoryStream())
{
using (
var compressor = new Ionic.Zlib.GZipStream(
output, Ionic.Zlib.CompressionMode.Compress,
Ionic.Zlib.CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
}
return output.ToArray();
}
}
//请求的单元测试
[TestMethod]
public void DeflateTest()
{
string html = string.Empty;
string postUrl = "http://localhost:8087/api/Contacts/DeflateTest";
string paramData = "userId=jlk456j5";
Encoding dataEncode = Encoding.UTF8;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
webReq.ContentLength = byteArray.Length;
//webReq.Headers["userId"] = DESHelper.Encrypt("1382888655");
//webReq.Headers["userPwd"] = DESHelper.Encrypt("123456789");
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
////0
////StreamReader sr = new StreamReader(response.GetResponseStream());
////html = sr.ReadToEnd();
////sr.Close();
//using (var s = response.GetResponseStream())
//{
// Encoding encode = Encoding.GetEncoding("utf-8");
// Byte[] read = new Byte[512];
// int bytes = s.Read(read, 0, 512);
// while (bytes > 0)
// {
// html += encode.GetString(read, 0, bytes);
// bytes = s.Read(read, 0, 512);
// }
//}
//2
Stream zipstream = response.GetResponseStream();
byte[] zipByte = ToByteArray(zipstream);
html = DeflateDecompress(zipByte);
response.Close();
newStream.Close();
}
catch (Exception ex)
{
string tt = "";
}
string twt = html;
//html = DESHelper.DesDecrypt(html);
}
private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
private string DeflateDecompress(byte[] buffer)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
ms.Write(buffer, 0, buffer.Length);
ms.Position = 0;
//using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
//{
// stream.Flush();
// int nSize = 16 * 1024 + 256; //假设字符串不会超过16K
// byte[] decompr
4000
essBuffer = new byte[nSize];
// int nSizeIncept = stream.Read(decompressBuffer, 0, nSize);
// stream.Close();
// return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept); //转换为普通的字符串
//}
using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
{
stream.Flush();
byte[] decompressBuffer = ToByteArray(stream);
int nSizeIncept = decompressBuffer.Length;
stream.Close();
return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept); //转换为普通的字符串
}
}
}
相关文章推荐
- C# 正则表达式抓取网页上某个标签的内容,并替换链接地址和图片地址
- C# 知识回顾 - 装箱与拆箱
- C# ini 文件解析库
- C#算法之判断一个字符串是否是对称字符串
- C#算法之判断一个字符串是否是对称字符串
- C#窗体传值方法总结
- C#中图片BYTE[]和base64string的相互转换
- C# Stream 和 byte[] 之间的转换
- C#+ArcEngine加载shape、栅格、access、mxd文件
- C#中一些字符串操作的常用用法
- C#关闭进程树
- C#逐行读取文件的方法
- 浅析C#深拷贝与浅拷贝
- C#下查找并杀死子进程(进程树)
- C#浅拷贝与深拷贝区别
- C# 写日志
- c#全宇宙最牛的编程软件
- 结构及其使用 struct (C#)
- C#显示当前日期时间
- 浅析C#中的“==”和Equals