问题
I'm using Retrofit
to manage my requests and want to make some tests to check de request size using or not using gzip.
By default does OkHttp
performs gzip compression to requests or it must be implemented with an interceptor?
I've added
@Headers({
"Accept-Encoding: gzip, deflate",
"Content-Encoding: gzip"
})
or:
@Headers({
"Content-Type: application/json;charset=utf-8",
"Accept: application/json"
})
to my requests and did not see any change on the request length.
回答1:
OkHttp will do transparent gzip on response bodies unless you disable the feature with this header:
Accept-Encoding: identity
回答2:
We can use this code
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url)
.addHeader("X-TOKEN", "Bearer " + Auth.getInstance(mContext).getToken())
.addHeader("Accept-Encoding", "gzip")
.build();
Response response = client.newCall(request).execute();
if (responseCode == 200) {
// Regular JSON parsing to model
ItemModel itemModel = LoganSquare.parse(response.body().byteStream(), ItemModel.class);
long responseSize = response.body().contentLength();
// Manually decompress GZIP?
ItemModel itemModel = LoganSquare.parse(new GZIPInputStream(response.body().byteStream()), ItemModel.class);
long responseSize = response.body().contentLength();
}
来源:https://stackoverflow.com/questions/41164299/okhttp-enable-disable-gzip-compression-on-requests