如何将使用 GZIP 压缩的字符串从 Java 应用程序发送到 PHP 网络服务

How to send string compressed with GZIP from Java App to PHP web service

我遇到 GZIP 压缩问题:

我需要通过 POST 方法发送一个巨大的 JSON 字符串,它太大而无法像 URL 那样接受(例如:http://localhost/app/send/JSON 由 BASE64 编码的字符串),而不是导致 HTTP 错误 403

所以,我需要压缩我的 json,我找到了一种使用 GZIP 压缩的方法,我可以在 PHP.

中使用 gzdecode() 解压缩

但是没用...

我的函数 compress() 和 decompress() 在我的 Java 应用程序中运行良好,但是当我将它发送到网络服务时,出现问题并且 gzdecode() 不起作用。 我不知道我错过了什么,我需要一些帮助

java 应用程序(客户端)中使用的函数

    public String Post(){
     String retorno = "";
     String u = compress(getInput());
     u = URLEncoder.encode(URLEncoder.encode(u, "UTF-8"));

     URL uri = new URL(url + u);

     HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

     conn.setDoOutput(false);
     conn.setRequestMethod(getMethod());

     conn.setRequestProperty("Content-encoding", "gzip");
     conn.setRequestProperty("Content-type", "application/octet-stream");

     BufferedReader buffer = new BufferedReader(
                    new InputStreamReader((conn.getInputStream())));

     String r = "";
     while ((r = buffer.readLine()) != null) {
                retorno = r + "\n";
     }
     return retorno;
}

GZIP压缩功能(客户端)

public static String compress(String str) throws IOException {

        byte[] blockcopy = ByteBuffer
                .allocate(4)
                .order(java.nio.ByteOrder.LITTLE_ENDIAN)
                .putInt(str.length())
                .array();
        ByteArrayOutputStream os = new ByteArrayOutputStream(str.length());
        GZIPOutputStream gos = new GZIPOutputStream(os);
        gos.write(str.getBytes());
        gos.close();
        os.close();
        byte[] compressed = new byte[4 + os.toByteArray().length];
        System.arraycopy(blockcopy, 0, compressed, 0, 4);
        System.arraycopy(os.toByteArray(), 0, compressed, 4,
                os.toByteArray().length);

        return Base64.encode(compressed);

    }

方法php用于接收URL(服务器,使用Slim/PHP框架)

init::$app->post('/enviar/:obj/', function( $obj ) {
     $dec = base64_decode(urldecode( $obj ));//decode url and decode base64 tostring
     $dec = gzdecode($dec);//here is my problem, gzdecode() doesn't work
}

post方法

public Sender() throws JSONException {   
    //
    url = "http://192.168.0.25/api/index.php/enviar/";
    method = "POST";
    output = true;
    //
}

如某些评论所述。

  1. 更大的数据应该作为 POST 请求而不是 GET 发送。 URL params 应该只用于单个变量。正如您注意到的 URL 长度限制为几 kB,以这种方式发送更大的数据并不是一个好主意(即使 GZIP 压缩)。

  2. 你的GZIP压缩码好像有误。请试试这个:

  public static String compress(String str) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream(str.length());
    GZIPOutputStream gos = new GZIPOutputStream(os);
    gos.write(str.getBytes());
    os.close();
    gos.close();
    return Base64.encodeToString(os.toByteArray(),Base64.DEFAULT);
  }