[英]Compressing with Java Decompressing with PHP
我有一種情況,servlet正在向PHP腳本提供壓縮數據。 我壓縮Java端的數據沒問題,但PHP似乎無法解壓縮。
以下是Java Side的相關代碼片段:
OutputStream o=response.getOutputStream();
GZIPOutputStream gz=new GZIPOutputStream(o);
gz.write(GridCoder.encode(rs,id, perPage, page).getBytes());
gz.close();
o.close();
PHP方面:
$xml= gzuncompress($xml);
有人可以指出我正確的方向。
我剛看到你的問題並對此感到好奇。 所以我做了自己的測試用例。 我把所有與Servlet相關的東西都留下了問題,編碼如下:
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class GZIPTestcase {
public static void main(String[] args) throws Throwable {
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(new File("/Users/malax/foo2.gz")));
PrintWriter pw = new PrintWriter(gzipOutputStream);
pw.println("All your base are belong to us!");
pw.flush();
pw.close();
}
}
GNU gunzip能夠解壓縮數據。 然后我嘗試用PHP解壓縮它。 它失敗了你得到的同樣的錯誤。 我進一步調查,發現了以下方法:
gzinflate也不起作用,gzdecode只附帶PHP6,我沒有安裝。 也許你可以試試這個。 (根據http://bugs.php.net/bug.php?id=22123這將有效)
我懷疑問題是在Java方面,因為GNU的gunzip可以縮小數據,因此它必須是正確的。 您可能希望在PHP方面進一步調查。
對於.NET和PHP存在一個問題,原始海報遇到了與您相同的問題: PHP可以解壓縮使用.NET GZipStream類壓縮的文件嗎? 。 PHP似乎無法從GZIPOutputStream的.NET等效解壓縮數據。
對不起,我沒有“解決方案”,但無論如何我可能已經指出了正確的方向。
編輯:我在PHP Bugtracker中找到了一個解釋問題的條目: http ://bugs.php.net/bug.php?id = 226967 gzuncompress似乎無法使用將生成GZIPOutputStream的標頭解壓縮GZIP數據。 如Bugtracker Entry中所述,嘗試裁剪標題。
嘗試使用DeflaterOutputStream而不是GZIPOutputStream
PHP函數調用libzlib實現DEFLATE。 Gzip完全是一個不同的野獸。
命名PHP函數gz XXX只會增加混亂。
我找到了一種解決方法,使用Devon_C_Miller和Malax的帖子作為指導。
java代碼:
String body = "Lorem ipsum shizzle ma nizle";
URL url = new URL("http://some.url/file.php?id=" + uid);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-encoding", "deflate");
conn.setRequestProperty("Content-type", "application/octet-stream");
DeflaterOutputStream dos = new DeflaterOutputStream(conn.getOutputStream());
dos.write(body.getBytes());
dos.flush();
dos.close();
PHP方面:
$content = http_get_request_body();
$uncontent = gzuncompress($content);
'Java Deflater + PHP gzuncompress '的組合為我工作。 客戶端:Android 4.1.1,服務器站點:php 5.3
在某些情況下,對於誰來尋找僅壓縮請求體的一部分的解決方案,例如我,使用HTTP表單發布一些參數和文件,以下是我在Android端使用的片段:
public static byte[] compressString(String data) throws IOException {
byte[] compressed = null;
byte[] byteData = data.getBytes();
ByteArrayOutputStream bos = new ByteArrayOutputStream(byteData.length);
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(byteData, 0, byteData.length);
compressor.finish();
// Compress the data
final byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
compressor.end();
compressed = bos.toByteArray();
bos.close();
return compressed;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.