java - reading deflated data from the stream using inflater and InflaterInputStream -
i'm trying send deflated string on http, when use compression , decompression on server side, without using streams, it's ok when write stream this:
byte[] deflateddata = mtext.getbyte(); try { t.sendresponseheaders(200,deflateddata.length); } catch (ioexception e1) { display(e1); e1.printstacktrace(); if(closeafter){ t.close(); } return; } deflateroutputstream os = new deflateroutputstream(t.getresponsebody()); try { os.write(deflateddata ,0,deflateddata .length); } catch (ioexception e1) { mbyte = null; display(e1); if(closeafter){ t.close(); } return; } os.flush(); os.close(); and read client side this:
inflaterinputstream ini = new inflaterinputstream(response.body().bytestream()); bytearrayoutputstream bout =new bytearrayoutputstream(512); int b; while ((b = ini.read()) != -1) { bout.write(b); } ini.close(); bout.close(); string s=new string(bout.tobytearray()); android decompresses this:
public static byte[] decompress(byte[] data) throws ioexception, dataformatexception{ inflater inflater = new inflater(); inflater.setinput(data); bytearrayoutputstream outputstream = new bytearrayoutputstream(data.length); byte[] buffer = new byte[1024]; while (!inflater.finished()) { int count = inflater.inflate(buffer); outputstream.write(buffer, 0, count); } byte[] output = outputstream.tobytearray(); outputstream.close(); inflater.end(); return output; } so following exception:
java.util.zip.dataformatexception: data error where going wrong?
the sending part totally ok , answer use inflaterinputstream directly input stream , this:
public static string readdeflateddata(inputstream input){ inflaterinputstream in = new inflaterinputstream(input, new inflater()); int bytesread=0; stringbuilder sb = new stringbuilder(); byte[] contents = null; try { contents = new byte[in.available()]; } catch (ioexception e2) { // todo auto-generated catch block e2.printstacktrace(); } try { while( (bytesread = in.read(contents)) != -1){ sb.append(new string(contents, 0, bytesread)); } } catch (ioexception e) { system.out.println(e.tostring()); e.printstacktrace(); } try { return new string(sb.tostring().getbytes(),"utf-8"); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } return null; }
Comments
Post a Comment