【问题标题】:Retrofit with okhttp is extremely slow even after Keep-Alive header即使在 Keep-Alive 标头之后,使用 okhttp 进行改造也非常慢
【发布时间】:2019-07-20 08:14:10
【问题描述】:

当我使用改造下载 json 文件时,每次都花费太多时间。

我正在使用 okhttp 进行改造来获取 json 数据并在 recyclerview 中显示。我正在使用拦截器来包含 keep-alive 标头。然而,与 google 的 firestore 数据库相比,请求需要相当长的时间。我认为保持活动无法正常工作,并且每个请求都在打开新连接,这就是加载时间过长的原因。

API 代码:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        ConnectionPool connectionPool = new ConnectionPool(10, 10, TimeUnit.MINUTES);

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.connectionPool(connectionPool)
                .connectTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES);
        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();

                Response response = chain.proceed(request);

                if (!response.isSuccessful() || response.code()==503) {
                    connectionPool.evictAll();
                    return chain.proceed(request);
                } else {
                    // Customize or return the response
                    return response;
                }
            }
        });
        OkHttpClient client = httpClient.build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
postService = retrofit.create(PostService.class);

public interface PostService {

    @POST
    Call<PostList> getPostList(@Url String url);
}

当我使用此代码时,通过 10mbps wifi 连接甚至 4G 连接加载 40kb 文件需要 8 秒以上。而从 firebase firestore 加载相同的数据几乎不需要 1 秒。

事实上,我从 firestore 查询了 400kb 的数据,加载只需要 4 秒,而从改造中提取的 400kb 文件需要很长时间,以至于应用程序实际上冻结了。

我使用 Glide 加载图片,Glide 加载 100kb 的图片不到 2 秒。

所以我想我在这里做错了什么,因为 Glide 非常快,firestore 非常快,只有使用 okhttp 进行改造非常慢。

谁能告诉我这里做错了什么?

谢谢。

【问题讨论】:

  • 好的,我解决了,当我通过改造下载一个普通文件并通过 InputStream 读取它时,它花费的时间太长了。但是当以 json 格式访问相同的数据时,它花费的时间不超过 1 秒。我认为改造应该只用于获取json数据而不是普通文件。

标签: android google-cloud-firestore retrofit2 okhttp3


【解决方案1】:

好的,我解决了,当我通过改造下载一个普通文件并通过 InputStream 读取它时,它花费的时间太长了。但是当以 json 格式访问相同的数据时,它花费的时间不超过 1 秒。我认为改造应该只用于获取json数据而不是普通文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2013-02-24
    • 2016-12-10
    • 1970-01-01
    • 2018-02-02
    相关资源
    最近更新 更多