gpt4 book ai didi

android - Retrofit 2 和 okhttp 3 的缓存错误

转载 作者:行者123 更新时间:2023-12-04 03:15:20 26 4
gpt4 key购买 nike

我正在尝试缓存来 self 公司 API 的 HTTP 响应,但应用程序似乎无法访问缓存目录:

W/System.err: remove failed: ENOENT (No such file or directory) :/data/user/0/com.appname/cache/cache_file/journal.tmp

W/System.err:java.net.UnknownHostException: Unable to resolve host"www.domain.com": No address associated with hostname

我已经关注了这个 tutorial .以下是我如何设置 Retrofit (2.1.0):

import lu.CompanyName.R;
import lu.CompanyName.interfaces.CompanyNameAPI;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static okhttp3.logging.HttpLoggingInterceptor.Level.HEADERS;


public class Injector {

private static final String CACHE_CONTROL = "Cache-Control";

private static Retrofit provideRetrofit (String baseUrl) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(provideOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
}

private static OkHttpClient provideOkHttpClient () {
return new OkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache())
.build();
}

private static Cache provideCache () {
/*
Cache cache = null;
try
{
File dir = CompanyName.getInstance().getExternalCacheDir();

if (dir == null)
dir = CompanyName.getInstance().getCacheDir();

if (dir == null)
Log.e("provideCache", "dir is null");

cache = new Cache(new File(dir, "http-cache"), 10 * 1024 * 1024); // 10 MB

if (cache == null)
Log.e("provideCache", "cache is null");

}
catch (Exception e)
{
Log.e("provideCache", "Could not create Cache!");
}
return cache;*/

/*
File httpCacheDirectory = new File(CompanyName.getInstance().getCacheDir(), "responses");
httpCacheDirectory.getParentFile().mkdirs();
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);
try {
cache.initialize();
Iterator<String> iterator = cache.urls();
Log.i("provideCache", "URLs in cacheHttpClient : ");
while (iterator.hasNext()) {
Log.i("provideCache", iterator.next());
}
} catch (IOException e) {
e.printStackTrace();
Log.i("provideCache", "CACHE NOT INIT");
}
return cache;*/

return new Cache(new File(CompanyName.getInstance().getCacheDir(), "cache_file"), 20 * 1024 * 1024);
}

private static HttpLoggingInterceptor provideHttpLoggingInterceptor () {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HEADERS);
return httpLoggingInterceptor;
}

private static Interceptor provideCacheInterceptor () {
/*return new Interceptor() {
@Override
public Response intercept (Chain chain) throws IOException {
Response response = chain.proceed(chain.request());

// re-write response header to force use of cache
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(2, TimeUnit.HOURS)
.build();

return response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build();
}
};*/
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
String cacheHeaderValue = CompanyName.getInstance().checkIfHasNetwork()
? "public, max-age=2419200"
: "public, only-if-cached, max-stale=2419200" ;
Request request = originalRequest.newBuilder().build();
Response response = chain.proceed(request);
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheHeaderValue)
.build();
}
};
}

private static Interceptor provideOfflineCacheInterceptor () {
/*return new Interceptor()
{
@Override
public Response intercept (Chain chain) throws IOException
{
Request request = chain.request();

if (!CompanyName.hasNetwork())
{
CacheControl cacheControl = new CacheControl.Builder()
//.maxStale(7, TimeUnit.DAYS)
.build();

request = request.newBuilder()
.cacheControl(cacheControl)
.build();
}

return chain.proceed(request);
}
};*/
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
String cacheHeaderValue = CompanyName.getInstance().checkIfHasNetwork()
? "public, max-age=2419200"
: "public, only-if-cached, max-stale=2419200" ;
Request request = originalRequest.newBuilder().build();
Response response = chain.proceed(request);
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheHeaderValue)
.build();
}
};
}

public static CompanyNameAPI provideCompanyNameAPI () {
return provideRetrofit(CompanyName.getInstance().getString(R.string.base_url)).create(CompanyNameAPI.class);
}
}

我尝试了一些在互联网和 stackoverflow 上找到的解决方案(仍在上面代码的注释中),因为起初我认为这是一个“缓存控制”重写问题。

我还向 list 添加了 READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE 权限,但它没有改变任何内容。

我错过了什么吗? (我正在使用 Android 6.0.1 API 23 的三星进行测试)

最佳答案

关于第一个错误,我们看一下为OkHttpClient提供的缓存目录:

    private static OkHttpClient provideOkHttpClient () {
return new OkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache())
.build();
}

您为多个 OkHttpClient 使用了相同的缓存目录,许多实例可能会相互踩踏,破坏响应缓存。要解决此问题,您可以只使用一次 OkHttpClient,使用它们的缓存配置它,并在所有地方使用同一个实例。您可以尝试如下:

    private static Retrofit provideRetrofit (String baseUrl) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}

private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache())
.build();

有关 OkHttpClient 缓存的更多信息,您可以查看 this link .

关于android - Retrofit 2 和 okhttp 3 的缓存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573748/

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