我使用OkHttp3。有时,API调用花费的时间比预期的要长,最多10秒。下次相同的通话可能要花几毫秒。
这是我的客户
private HttpClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.e(TAG, message);
}
});
if (BuildConfig.DEBUG_VERSION.equals(BuildConfig.VERSION_NAME)) {
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
}
retryRequestInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
int retryCode = 429; //retry request if this code received
int tryCount = 0;
int maxLimit = 1;
while (response.code() == retryCode && tryCount < maxLimit) {
Log.e(TAG, "Request failed, got " + response.code() + ". Retrying");
tryCount++;
response = chain.proceed(request);
}
return response;
}
};
cache = new Cache(AppContext.getContext().getCacheDir(), cacheSize);
client = buildClient(builder);
request = new Request.Builder()
.addHeader("Content-Type", "application/vnd.api+json");
String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;
if (versionCode < 0) {
versionName = versionName.replaceFirst(String.valueOf(versionCode), "0-dev");
}
request.header("User-Agent", "NTR/" + String.valueOf(versionName));
}
private OkHttpClient buildClient(OkHttpClient.Builder builder) {
builder.addInterceptor(httpLoggingInterceptor);
builder.addInterceptor(retryRequestInterceptor);
builder.cache(cache);
return builder.build();
}
public static HttpClient getInstance() {
if (instance == null) {
instance = new HttpClient();
}
return instance;
}
我添加了HttpLoggingInterceptor并得到了
12-30 05:34:41.342 2400 10846 E DEBUG : 0.001 connectionAcquired
12-30 05:34:41.353 2400 10846 E DEBUG : 0.013 requestHeadersStart
12-30 05:34:41.354 2400 10846 E DEBUG : 0.014 requestHeadersEnd
12-30 05:34:41.354 2400 10846 E DEBUG : 0.014 requestBodyStart
12-30 05:34:41.355 2400 10846 E DEBUG : 0.014 requestBodyEnd
12-30 05:34:41.358 2400 10846 E DEBUG : 0.017 responseHeadersStart
12-30 05:34:45.435 2400 10846 E DEBUG : 4.095 responseHeadersEnd
总是在头开始和结束之间出现延迟。
为什么会发生?