将Apollo客户端与okHttpClient客户端一起使用。
Apollo库使用okhttpClient处理请求响应。我的App对OKHttpClient的请求和响应没有做任何事情。
使用以下代码创建Apollo客户端:
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.connectTimeout(queryTimeout, TimeUnit.SECONDS)
.readTimeout(queryTimeout, TimeUnit.SECONDS)
.writeTimeout(queryTimeout, TimeUnit.SECONDS)
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.header("Authorization", getAuthorizationValue())
.build();
return chain.proceed(request);
})
.build();
return new ApolloClient(com.apollographql.apollo.ApolloClient.builder()
.serverUrl(graphqlEndPoint)
.okHttpClient(okHttpClient)
.build());
应用发出警告
2019-04-10 05:59:19.421 WARN 52654 --- [OkHttp ConnectionPool] okhttp3.OkHttpClient : A connection to http://127.0.0.1/ was leaked. Did you forget to close a response body?
以下问题对我不起作用:
OkHttp: avoid leaked connection warning
OkHttp: A connection to http://example.com/ was leaked. Did you forget to close a response body?
Apollo客户端查询用法(按要求):
this.client.query(query).enqueue(callback);
回调实现:
@Slf4j
public class SyncableCallback<T> extends ApolloCall.Callback<T> {
private CompletableFuture<T> completableFuture = new CompletableFuture<>();
@Override
public void onResponse(@Nonnull Response<T> response) {
log.debug("Response received: {}", response.data());
completableFuture.complete(response.data());
}
@Override
public void onFailure(@Nonnull ApolloException e) {
completableFuture.completeExceptionally(e);
}
public T getResult() throws ClientException {
try {
return completableFuture.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ClientException(e);
} catch (ExecutionException e) {
throw new ClientException(e);
}
}
}