Http 請求和響應的gzip壓縮
阿新 • • 發佈:2019-01-04
通過請求和響應頭中增加
Accept-Encoding: gzip
Content-Encodin:gzip
確定客戶端或伺服器端是否支援壓縮
舉例,客戶端傳送請求,服務端壓縮響應資料返給客戶端
1、客戶端請求中增加Accept-Encoding: gzip表示客戶端支援gzip;
2、服務端接收到請求後,將結果通過gzip壓縮後返回給客戶端並在響應頭中增加Content-Encodin:gzip 表示響應資料已被壓縮
3、客戶端接收請求,響應頭中有Content-Encodin:gzip表示資料需解壓處理
客戶端也可以傳送壓縮資料給服務端,通過程式碼將請求資料壓縮即可,規範起見同樣要在請求中加入Content-Encodin:gzip
OkHttp壓縮資料:
private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; }
public RequestBody getGzipRequest(String body) { RequestBody request = null; try { request = RequestBody.create(MediaType.parse("application/octet-stream"),compress(body)); } catch (IOException e) { e.printStackTrace(); } return request; }
OkHttp解壓(自動響應gzip解壓):
通過BridgeInterceptor類攔截響應,自動處理gzip解壓
通過GZIPOutputStream、GZIPInputStream壓縮和解壓:
public static byte[] compress(String str) throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return out.toByteArray();
//return out.toString(StandardCharsets.ISO_8859_1);
// Some single byte encoding
}
}
public static String uncompress(byte[] str) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str))) {
int b;
while ((b = gis.read()) != -1) {
baos.write((byte) b);
}
}
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}