user2005049 user2005049 - 1 month ago 14
Android Question

Delphi: How to set TWebResponse to contain gzip and read it in Android App?

I'm building a WebServer for Android App.(WebBroker->VC).

How can I compress my response string to gzip, I tried this:

a:=[{.......}];//json data
srcbuf := BytesOf(a.ToString);
ZCompress(srcbuf, destbuf, zcDefault);
Response.Content := '';
Response.ContentStream := TMemoryStream.Create;
Response.ContentEncoding := 'deflate';
Response.ContentType := 'application/json';
Response.ContentStream.Write(@(destbuf[0]),length(destbuf));
Response.ContentLength := (length(destbuf));


In my android app I get error:

Uknown format (magic number...)

I also have server side written in PHP and android app works fine, I think that Delphi System.ZLib doesn't compress as gzip?

Any idea how solve this?

Answer

I found the solution:

Delphi:

//------------------------------------------------------------------------------
procedure doGZIP(Input, gZipped: TMemoryStream);//helper function
const
  GZIP = 31;//very important because gzip is a linux zip format
var
  CompactadorGZip: TZCompressionStream;
begin
  Input.Position:=0;
  CompactadorGZip:=TZCompressionStream.Create(gZipped, zcMax, GZIP);
  CompactadorGZip.CopyFrom(Input, Input.Size);
  CompactadorGZip.Free;
  gZipped.Position:=0;
end;
//------------------------------------------------------------------------------
.
.
.
strJSON:=a.ToString;//a->TJSONArray
 //init
 Original:=TMemoryStream.Create;
 gZIPStream:=TMemoryStream.Create;
 //copy result to stream
 oString := UTF8String(strJSON);
 len := length(oString);
 Original.WriteBuffer(oString[1], len);
 //make it gzip
 doGZIP(Original,gZIPStream);
 //prepare responsestream and set content encoding and type
 Response.Content := '';
 Response.ContentStream:=gZIPStream;
 Response.ContentEncoding := 'gzip';
 Response.ContentType := 'application/json';
 //clear...
 Original.Free;

Android:

conn.setRequestProperty("Accept-Encoding", "gzip");//do not forget this
Comments