[英]Decompression of a string sent from c# to PHP
这是将要发送到php代码的字符串压缩的函数
public string Zip(string value)
{
//Transform string into byte[]
byte[] byteArray = Encoding.UTF8.GetBytes(value);
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
//Prepare for compress
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Compress);
//Compress
sw.Write(byteArray, 0, byteArray.Length);
//Close, DO NOT FLUSH cause bytes will go missing...
sw.Close();
//Transform byte[] zip data to string
byteArray = ms.ToArray();
System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
foreach (byte item in byteArray)
{
sB.Append((char)item);
}
ms.Close();
sw.Dispose();
ms.Dispose();
return sB.ToString();
}
我正在使用发送请求
string data = req.Zip(xml);
string resp = req.post(url,"&Data="+data);
我试图使用gzuncompress,gzdecode,但所有产生数据错误,任何人都知道为什么?
这段代码很奇怪:
byte[] byteArray = Encoding.UTF8.GetBytes(value);
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
您正在使用UTF-8编码将其转换为字节数组... 然后您通过将每个字符转换为一个字节来覆盖该数组的内容(或该数组的至少一些内容) - 这是有效地应用ISO-Latin-1编码。
然后,您将任意二进制数据转换为如下字符串:
byteArray = ms.ToArray();
System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
foreach (byte item in byteArray)
{
sB.Append((char)item);
}
不要那样做。 这是不透明的二进制数据 - 您正在创建的“字符串”(再次,通过ISO-8859-1有效创建)可以正确转移的可能性非常小。
将任意二进制数据编码为字符串时,您几乎应该始终使用Base64:
string base64 = Convert.ToBase64String(byteArray);
然后,您还将数据用作URL编码的表单数据 - 尽管字符串可以很容易地包含诸如&
和%
字符,这些字符在URL编码文本中具有特殊含义。 不要这样做。
基本上,你应该:
using
语句) 要解压缩,您显然需要在解压缩之前执行base64到二进制转换。
如果可能的话,将压缩数据作为二进制数据而不是URL编码的表单参数发布将更加有效(就传输的数据而言)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.