首页 > 解决方案 > Transferring large amounts of data from PHP to Android using compressed JSON

问题描述

I have to transfer 9.7MB of JSON data from a PHP server to Android devices. The data is compressed using gzencode() and decompressed on the device, then stored in a SQLite database. The whole download process takes about 55 seconds or more depending on network speed.

How can I shorten the download time / optimize the process?

I tried caching the text to file and then sending it instead at each request, but the speed did not improve. Neither splitting the file into chunks.

Even with download speeds of 40-50MB/s nothing improves.

<?php
if (isset($_POST['confirmare'])) {
header('Content-Type: application/json');

require "../conexiune.php";
$cat = $_POST['confirmare'];
$sql    = "SELECT ID, Text, Răspuns1, Răspuns2, Răspuns3, Imagine, Categorie, ImagineBlob FROM Întrebări Where Categorie = '$cat'";
$result = $conn->query($sql);
ob_start('ob_gzhandler');

class întrebare
{
    public $ID;
    public $Text;
    public $Răspuns1;
    public $Răspuns2;
    public $Răspuns3;
    public $Imagine;
    public $Categorie;
    public $ImagineGen;
    public function __construct($IDp, $Textp, $Răspuns1p, $Răspuns2p, $Răspuns3p, $Imaginep, $Categoriep, $ImagineGenp)
    {
        $this->ID      = $IDp;
        $this->Text    = $Textp;
        $this->Răspuns1      = $Răspuns1p;
        $this->Răspuns2      = $Răspuns2p;
        $this->Răspuns3      = $Răspuns3p;
        $this->Imagine = $Imaginep;
        $this->Categorie = $Categoriep;
        $this->ImagineGen =base64_encode($ImagineGenp);
    }
}
if ($result->num_rows > 0) {
    $string = "[";
    while ($row = $result->fetch_assoc()) {
        $obiect = new întrebare($row["ID"], $row["Text"], $row["Răspuns1"], $row["Răspuns2"], $row["Răspuns3"], $row["Imagine"], $row['Categorie'], $row['ImagineBlob']);
        $string .= json_encode($obiect) . ",";
    }
    $string = rtrim($string, ",");
    $string .= "]";
    $gzdata = gzencode($string, 9);
    echo $gzdata;
} else {
    echo "fără rezultate";
}
$conn->close();
}

标签: phpandroidjson

解决方案


I'm answering this in case someone else stumbles across this issue. The problem is that no matter how much you compress and optimize the process, there are a lot of bytes to be transferred especially if you encode your images in base64.

To solve this issue, I created a new table where I store all my images. When I send the objects from the server to the Android / iOS device, I only send the id to the image for each object. When the device needs to display the image, it creates an async request to the server with the image ID. This way only one image is downloaded at a time. Solving the issue and making download times insignificant.

Hope this helps, I've been stumbling a lot on this issue for the past year.


推荐阅读