Декомпрессия Zlib в Java не работает

Я сжимаю строку в PHP 5.4.4-14+deb7u7 с помощью

$cdat = gzcompress($dat, 9);

http://php.net/manual/en/function.gzcompress.php

Затем в Android / Java я хочу распаковать его, отсюда:
Android: распаковать строку, которая была сжата с помощью PHP gzcompress ()

Я использую:

public static String unzipString(String zippedText) {
String unzipped = null;
try {
byte[] zbytes = zippedText.getBytes("ISO-8859-1");
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString();
} catch (IOException e) {
}
return unzipped;
}

Но когда я попробовал это, он распаковался в пустую строку, когда загруженная сжатая строка в Android была очень длинной.

Скачанная строка была похожа

x�͜{o�8�a`�= �!�����[��K!(6c�E�$��]�)�HF��F\!����ə���L�LNnH]Lj٬T��M���f�'�u#�*_�7'�S^�w��*kڼn�Yޚ�I��e$.1C��~�ݟ��F�A�_Mv_�R͋��ܴ�Z^L���sU?A���?�׮�ZVmֽ6��>�B��C�M�*����^�sٸ�j����������?�"_�j�ܣY�E���h0�g��w[=&�D �oht=>�l�?��Po";`.�e�E�E��[���������sq��0���i]��������zUL�O{П��ժ�k��b�.&7��-d1_��ۣ�狝�y���=F��K!�rC�{�$����c�&9ޣH���n�x�

Кто-нибудь знает в чем проблема?

Благодарю.

public static Pair<String,Integer> GetHTTPResponse(String url, List<NameValuePair> urlparameters) {
String responseVal = null;
int responseCode = 0;

try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = TIMEOUT_SECONDS * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = TIMEOUT_SECONDS * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);

httppost.setEntity(new UrlEncodedFormEntity(urlparameters));
HttpResponse response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

responseVal = Common.GetStringFromBufferedReader(rd);

Log.d("SERVER", responseVal);
}
catch (Exception e) {
responseCode = 0;
}

if (responseVal != null) {
responseVal = Common.unzipString(responseVal);
}

return new Pair<String, Integer>(responseVal, responseCode);
}

1

Решение

Вы не можете использовать

BufferedReader rd =
new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
responseVal = Common.GetStringFromBufferedReader(rd);

Как InputStreamReaderJavadoc отмечает,

InputStreamReader является мостом от байтовых потоков к символьным потокам: он считывает байты и декодирует их в символы с использованием указанного charset,

Вместо этого вы можете использовать HttpEntity.writeTo(OutputStream) и ByteArrayOutputStream лайк

ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] content = baos.toByteArray();

Затем вы можете напрямую передать содержимое вашей функции в этом byte[], а также никогда молча проглотить Exception,

public static String unzipString(byte[] zbytes) {
String charsetName = "ISO-8859-1";
String unzipped = null;
try {
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString(charsetName);
} catch (IOException e) {
e.printStackTrace();
}
return unzipped;
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector