Android Code Snippet GZIP: B4x & PHP via okHttpUtils

Often transfered data (esp. JSON fromatted) get's huge. This is about to GZIP encode in PHP and decode in B4X. Like every data manipulation (encryption, zipping) it is BYTE based. So the main thing is to convert it between bytes and string format.

Libs: jRandomAccessFile

PHP: GZENCODE needs a STRING as input. So just encode the data it to a JSON string first (here I need to zip an array)

B4X:
$q = mysqli_query($con,"SELECT * FROM sometable") or die(mysqli_error($con));
$rows = array();
while($r = mysqli_fetch_assoc($q))
{
    $rows[] = $r;
}
      
$compressed = gzencode(json_encode($rows), 9);
print $compressed;

B4x: In Job.Done we use RAF's CompressedStreams:

B4X:
Dim OS As OutputStream 'Get the bytes from Job.InputStream
OS.InitializeToBytesArray(1000)
File.Copy2(Job.GetInputStream, OS)
Dim Buffer() As Byte
Buffer = OS.ToBytesArray
                  
Dim compress As CompressedStreams
Dim decompressed() As Byte
decompressed = compress.DecompressBytes(Buffer, "gzip")
                  
Dim DecompressedString As String 'convert Bytes to String again
DecompressedString=BytesToString(decompressed, 0, decompressed.Length, "UTF8")
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
A bit more compact version of this code:
B4X:
Dim Buffer() As Byte = Bit.InputStreamToBytes(Job.GetInputStream)
Dim compress As CompressedStreams
Dim decompressed() As Byte = compress.DecompressBytes(Buffer, "gzip")
Dim DecompressedString As String = BytesToString(decompressed, 0, decompressed.Length, "UTF8")
 

sorex

Expert
Licensed User
Longtime User
compressed output of HTTP content is a (default turned off) feature for years now on Apache/IIS.

Does OKhttp handle this?

If it does you don't need all this compression and decrompression code at all but just enable this feature.
 
Top