Delphi 客戶端 ↔ J2EE 伺服器端,XML 資料交換,引入 Zlib 壓縮降低頻寬,雙端需互通解壓。
public class ZlibUtils {
// 解壓:Base64 解碼 → InflaterOutputStream → 字串
public static String decompress(String base64Data) {
try {
byte[] decoded = Base64.getDecoder().decode(base64Data);
try (ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
InflaterInputStream iis = new InflaterInputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] buf = new byte[1024];
int len;
while ((len = iis.read(buf)) != -1) bos.write(buf, 0, len);
return bos.toString(StandardCharsets.UTF_8);
}
} catch (Exception e) { throw new RuntimeException("UNZIP_ERR", e); }
}
// 壓縮:字串 → DeflaterOutputStream → Base64 編碼
public static String compress(String data) {
try {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(bos)) {
dos.write(data.getBytes(StandardCharsets.UTF_8));
dos.finish();
return Base64.getEncoder().encodeToString(bos.toByteArray());
}
} catch (Exception e) { throw new RuntimeException("ZIP_ERR", e); }
}
}
function Cmip_CompressStr(txt: PChar): PChar; stdcall;
var
zip: TVclZip;
compressed: string;
begin
zip := TVclZip.Create(nil);
try
compressed := zip.ZLibCompressString(txt);
Result := StrNew(PChar(Base64EncodeStr(compressed)));
finally
zip.Free;
end;
end;
function Cmip_DeCompressStr(txt: PChar): PChar; stdcall;
var
unzip: TVCLUnZip;
decompressed: string;
begin
unzip := TVCLUnZip.Create(nil);
try
decompressed := unzip.ZLibDecompressString(Base64DecodeStr(txt));
Result := StrNew(PChar(decompressed));
finally
unzip.Free;
end;
end;
StrNew/呼叫端釋放)。Java 端可升級 java.util.Base64 (Java 8+);Delphi 可用 System.ZLib (XE2+) 移除第三方依賴;跨語言序列化建議改用 Protobuf/Avro + gzip,效能與演進性更優。