使用gzip的Android defaultHttpClient发布请求

时间:2015-03-16 08:20:42

标签: android tomcat gzip androidhttpclient

我正在尝试从我的android客户端向包含1MB +大小的字符串的tomcat服务器发送post请求。我在server.xml中启用了GZIP,并且我尝试了几种从客户端压缩该字符串的方法,但似乎它没有改变它的大小(我使用DDMS和wireshark来监视字符串的大小)。

发布请求(我将stringEntity更改为ByteArrayEntity以进行压缩和解压缩):

HttpPost httpPost = new HttpPost(url);

httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "");
httpPost.setHeader("Content-Encoding", "gzip");

StringWriter out = new StringWriter();
out.write(data);

sMsg = out.toString();
byte[] sMsgByte = compress(sMsg);
be = new ByteArrayEntity(sMsgByte);
httpPost.setEntity(be);
//se = new StringEntity(sMsg);
//httpPost.setEntity(se);
HttpResponse execute = httpClient.execute(httpPost);

压缩/解压缩:

public static byte[] compress(String str) throws Exception {
    if (str == null || str.length() == 0) {
        return str.getBytes();
    }
    ByteArrayOutputStream obj=new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.close();
    return obj.toByteArray();
}
public static byte[] compress2(String str) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = null;

    try {
        gzos = new GZIPOutputStream(baos);
        gzos.write(str.getBytes("UTF-8"));
    } finally {
        if (gzos != null) try { gzos.close(); } catch (IOException ignore) {};
    }

   return baos.toByteArray();
}

public static String decompress(byte[] bytes) throws Exception {
    if (bytes == null || bytes.length == 0) {
        return bytes.toString();
    }
    GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
    BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
    String outStr = "";
    String line;
    while ((line=bf.readLine())!=null) {
        outStr += line;
    }
    return outStr;
}

我做错了什么?

0 个答案:

没有答案