gpt4 book ai didi

安卓-OKHttp : how to enable gzip for POST

转载 作者:太空狗 更新时间:2023-10-29 16:11:14 24 4
gpt4 key购买 nike

在我们的 Android 应用程序中,我正在向我们的 (NGINX) 服务器发送相当大的文件,因此我希望对我的 Retrofit POST 消息使用 gzip。

有许多关于 OkHttp 透明地使用 gzip 或更改 header 以接受 gzip(即在 GET 消息中)的文档。

但是我如何启用此功能以从我的设备发送 gzip http POST 消息?我是否必须编写自定义拦截器或其他东西?或者只是在标题中添加一些东西?

最佳答案

根据以下recipe :gzip 的正确流程应该是这样的:

OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new GzipRequestInterceptor())
.build();

/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
static class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(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();
}
};
}
}

关于安卓-OKHttp : how to enable gzip for POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com