繁体   English   中英

如何将使用GZIP压缩的字符串从Java App发送到PHP Web服务

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

我有GZIP压缩这个问题:

我需要通过POST方法发送一个巨大的JSON字符串,这个字符串太大而不能接受像URL(例如: http:// localhost / app / send / JSON STRING ENCODED by BASE64 ),而不是导致HTTP错误403

所以,我需要压缩我的json,我找到了一种方法来使用GZIP压缩,我可以用PHP中的gzdecode()解压缩。

但它不起作用......

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

java app(client)中使用的函数

    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 Framework)

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
}

发布方法

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

正如一些评论中所注意到的那样。

  1. 较大的数据应作为POST请求而不是GET发送。 URL参数只能用于单个变量。 正如您所注意到的,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);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM