forked from segmentio/analytics-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGzipRequestInterceptor.java
More file actions
50 lines (44 loc) · 1.4 KB
/
Copy pathGzipRequestInterceptor.java
File metadata and controls
50 lines (44 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package sample;
import java.io.IOException;
import okhttp3.*;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;
/**
* This interceptor compresses the HTTP request body. Copied from
* https://github.com/square/okhttp/wiki/Interceptors#rewriting-requests
*/
final class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest =
originalRequest
.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
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();
}
};
}
}