C# Deflate 压缩与解压缩
来源:互联网 发布:图书销售软件 编辑:程序博客网 时间:2024/05/12 02:39
//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[] decompressBuffer = 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# Deflate 压缩与解压缩
- C# Deflate、GZip压缩与解压缩
- c# Deflate压缩与解压缩函数
- c#压缩解压缩bzip2、tar、zip、gzip、deflate、ntdll
- C#压缩与解压缩文件
- c#字符串压缩与解压缩
- C#实现压缩与解压缩
- C# 文件压缩与解压缩
- 解压缩PNG deflate压缩IDAT数据
- C#压缩与解压缩(zip文件)
- C#压缩与解压缩(zip文件)
- C#如何压缩与解压缩文件
- C#调用WinRAR实现压缩与解压缩
- C# 中压缩与解压缩的方法
- C#对ZIP的压缩与解压缩
- C# 使用SharpZip压缩与解压缩
- C# GZip、Deflate 压缩解压算法函数
- C# 压缩、解压缩文件
- github常见操作和常见错误!错误提示:fatal: remote origin already exists.
- 百度经纬度和google经纬度互转
- 《Java课程实习》日志(周三)
- arm-none-linux-gnueabi交叉工具链安装 ,介绍,区别总结
- 敏捷开发中的10大错误认识
- C# Deflate 压缩与解压缩
- 在PyCharm里配置SubVersion
- 锐评:手游安全破“黑”行动
- zBar扫描二维码时闪光灯自动打开问题
- 点双连通分量的求解 Tarjan算法的拓展
- C3P0数据库连接池的配置
- C# post数据时 出现如下错误: System.Net.WebException: 操作超时
- [Objective-C] Categories 小例子
- iOS UINavigationController跳转到指定页面