okHttp3保持活动连接不起作用

时间:2019-08-12 08:18:20

标签: android retrofit2 okhttp3

我正在使用带有Retrofit2的okhttp3来获取json文件。我尝试了所有使用Keep-Alive连接的方法,以使数据下载速度更快,但似乎没有任何效果。

我已经实现了拦截器并添加了keep-alive标头。但似乎只是不想工作。有人可以看看我的代码,然后告诉我我在做什么错吗?这是我的代码:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
ConnectionPool connectionPool = new ConnectionPool(3, 10, TimeUnit.MINUTES);
Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.connectionPool(connectionPool)
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS);
        httpClient.interceptors().add(logging);
        httpClient.interceptors().add(new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                Request original = chain.request();

                // Customize the request
                Request request = original.newBuilder()
                        .header("Connection", "Keep-Alive")
                        .method(original.method(), original.body())
                        .build();

                try {
                    Response response = chain.proceed(request);
                    if (!response.isSuccessful()) {
                            response.close();
                            connectionPool.evictAll();
                            Log.d("okokok", "evict");
                            return chain.proceed(request);
                        } else {
                            // Customize or return the response
                            Log.d("okokok", "return response");
                            return response;
                        }
                } catch (IOException e) {
                    e.printStackTrace();
                    connectionPool.evictAll();
                    return chain.proceed(request);
                }
            }
        });

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = new Retrofit.Builder()

                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();

        postService = retrofit.create(PostService.class);

根据此代码,标头应包含Keep-Alive,并且连接至少一分钟不应关闭。

我还检查了我的服务器,发现它确实接受Keep-Alive标头,并且在GTMatrix测试中还显示Keep-Alive确实在我的服务器上工作。但是由于某种原因,Android应用程序会保持关闭连接,并且每次我加载新文件时,都要花费一些时间与服务器建立新连接。

我在Firebase实时数据库中进行了尝试,并保存了json数据。当我从那里查询时,我惊讶地发现数据下载速度与第一次查询的改造速度完全相同,但是在第一次查询之后,每隔一个查询就会花费毫秒来加载数据。这意味着比改造快10至20倍。

我想在这里添加的一件事是,我正在使用Glide从服务器加载图像,而Glide似乎很好地使用了Keep-Alive设置,因为Glide非常高效地加载了图像,没有任何延迟。因此,下载速度缓慢的问题似乎只与okhttp3 + Retrofit有关。

有人可以调查一下,让我知道我在这里做错了吗?我已经在这个问题上工作了2个星期,但仍然没有找到解决方案。我阅读了与此问题有关的每个stackoverflow问题,但似乎无济于事。

1 个答案:

答案 0 :(得分:0)

好的,这段代码可以正常工作,我发现我的主机的keepAliveTimeout限制为5秒,这就是为什么KeepAlive只能工作5秒并在连接关闭后起作用的原因。除非我更改主机,否则无论我如何明智地进行代码操作都无法更改此设置。