//1 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) };
}
[GZipCompression]
[HttpPost]
public HttpResponseMessage GZipTest()
{
string httpRequestMessage = string.Format("{{\"status\":\"{0}\",\"message\":\"{1}\",\"userInfo\":{2}}}", "12", "GZipCompression压缩POST测试!", "[]");
return new HttpResponseMessage { Content = new StringContent(httpRequestMessage) };
}
//2 写在 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 GZipCompressionAttribute : 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.GZipByte(bytes);
actContext.Response.Content = new ByteArrayContent(zlibbedContent);
actContext.Response.Content.Headers.Remove("Content-Type");
actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
//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();
}
}
}
//3
[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("1388655");
//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);
}
[TestMethod]
public void GZipTest()
{
string html = string.Empty;
string postUrl = "http://localhost:8087/api/Contacts/GZipTest";
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("1382655");
//webReq.Headers["userPwd"] = DESHelper.Encrypt("123456789");
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
Stream zipstream = response.GetResponseStream();
byte[] zipByte = ToByteArray(zipstream);
html = GZipDecompress(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); //转换为普通的字符串
}
}
}
private string GZipDecompress(byte[] buffer)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
ms.Write(buffer, 0, buffer.Length);
ms.Position = 0;
using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(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); //转换为普通的字符串
}
}
}