0
我試圖用gunzip壓縮字符串,對其進行編碼,通過URL傳遞它(GET請求),並對其進行解碼和解壓縮。我在壓縮之後進行Base64編碼,因爲根據我的理解,gunzip創建一個字節流,並將其直接轉換爲字符串會變得有點冒險。我似乎無法正確解壓縮 - 我通常會得到一個EOF異常。我用下面的測試:使用gunzip壓縮/解壓縮字符串
String compressed = myClass.compressStr(testStr);
String uncompressed = myClass.decompressStr(compressed);
Assert.assertEquals(testStr, uncompressed);
,我用它來推動這個看起來像這樣的代碼:
public static byte[] gzipCompress(byte[] bytes, int offset, int length)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
try
{
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);
gzipOutputStream.write(bytes, offset, length);
gzipOutputStream.flush();
gzipOutputStream.close();
return baos.toByteArray();
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
public static byte[] gzipUncompress(byte[] src, int offset, int len)
{
ByteArrayInputStream bais = new ByteArrayInputStream(src, offset, len);
try
{
GZIPInputStream gzipInputStream = new GZIPInputStream(bais);
return ByteStreams.toByteArray(gzipInputStream);
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
public static String compressStr(String someStr) throws
UnsupportedEncodingException
{
final byte[] foo = Base64.decodeBase64(
someStr.getBytes("utf-8"));
final byte[] gunzippedBytes = CompressUtil.gzipCompress(
foo,
0,
foo.length - 1);
return Base64.encodeBase64String(gunzippedBytes);
}
public static String decompressStr(String compressedStr)
throws UnsupportedEncodingException
{
final byte[] compressedBytes = Base64.decodeBase64(
compressedStr);
final byte[] gunzippedBytes = CompressUtil.gzipUncompress(
compressedBytes,
0,
compressedBytes.length - 1);
return Base64.encodeBase64String(gunzippedBytes);
}
什麼編碼的正確排序/解碼字符串?我猜測我正在大肆渲染一些東西。