java http 压缩_解压HTTP API的GZIP压缩数据
1.對Java后端的請求HttpURLConnection對象中的消息頭設置壓縮
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
2.發送請求后獲取response中的content-encoding
connection.getContentEncoding(); // 獲取content-encoding
3.如果content-encoding == gzip,則將獲取到的字節流轉為字節數組(壓縮),然后再將字節數組解壓
public static byte[] uncompresss(byte[] bytes) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int n;
while((n = gzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
gzip壓縮字符串為字節數組
/**
* 將字符串進行gzip壓縮,輸出壓縮后的字節數組
*/
public static byte[] compress(String str, String encoding) throws Exception {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
return out.toByteArray();
}
總結
以上是生活随笔為你收集整理的java http 压缩_解压HTTP API的GZIP压缩数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java按条件查询结果为空_mybati
- 下一篇: 上古情歌每周更新几集 小说结局赤云牺牲自