android - 即使在 Keep-Alive 标头之后,使用 okhttp 进行改造也非常慢
问题描述
当我使用改造下载 json 文件时,每次都花费太多时间。
我正在使用带有 okhttp 的改造来获取 json 数据并在 recyclerview 中显示。我也在使用拦截器来包含 keep-alive 标头。然而,与 google 的 firestore 数据库相比,请求需要相当长的时间。我认为保持活动无法正常工作,并且每个请求都在打开新连接,这就是加载时间过长的原因。
接口代码:
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 数据而不是普通文件。
推荐阅读
- c++ - 如何在eclipse中获取空格而不是制表符
- python - 如何使用pyspark从字符串中提取数字格式
- java - 在 RecyclerView 中嵌入 PlaceAutocompleteFragment
- visual-studio-code - Ubuntu 18.04 上 VS Code v1.0.0 中的接口错误
- javascript - PhantomJS 仍然可行吗?
- sapui5 - 用另一个对象的属性扩展对象
- excel - PowerShell + Excel.Application 添加工作表问题
- python - 在 Django 上实现多层角色
- actions-on-google - Google Smart Home SYNC 抛出错误:无法更新设置。请检查您的连接
- ios - 在将文件上传到 iOS 的服务器之前设置文件大小限制