Android-OKHttp:如何为POST启用gzip [英] Android - OKHttp: how to enable gzip for POST

查看:118
本文介绍了Android-OKHttp:如何为POST启用gzip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In our Android App, I'm sending pretty large files to our (NGINX) server so I was hoping to use gzip for my Retrofit POST message.

有很多关于OkHttp的文档,它们透明地使用gzip或更改标题以接受gzip(即在 GET 消息中).

There are many documentations about OkHttp using gzip transparently or changing the headers in order to accept gzip (i.e. in a GET message).

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

But how can I enable this feature for sending gzip http POST messages from my device? Do I have to write a custom Intercepter or something? Or simply add something to the headers?

推荐答案

根据以下

According to the following recipe: The correct flow for gzip would be something like this:

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();
        }
      };
    }
  }

这篇关于Android-OKHttp:如何为POST启用gzip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆