簡體   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