use of okhttp3.Dispatcher in project BestPracticeApp by pop1234o.
the class MainActivity method requestOkHttpGet.
/**
* ==============================
* 先用Builder模式来构建Request对象,然后将Request封装成一个Call(RealCall)对象
* 调用RealCall.execute。里面使用OkHttpClient.Dispatcher.execute(call)
* 里面将call加入Dispatcher中ArrayDeque中,然后再 RealCall.getResponseWithInterceptorChain()
* 中创建各种拦截器,(
* BridgeInterceptor 添加请求头,比如User-Agent,Connection,Host
* CacheInterceptor请求头缓存设置,
* ConnectInterceptor获取http连接,判断是1.0还是1.1,
* 获取到HttpCodec对象,真正建立起了Socket连接
* CallServerInterceptor 将请求行,请求头写入Socket,然后发送到服务端,接收Socket响应
* 这里用的是BufferedSource 是okio,NIO,然后获取到http响应,解析响应行,响应头,响应体
* 用ResponseBuilder来创建一个Response,然后返回
* )
* 以上是一个同步的过程,异步的过程类似,就是创建一个AsyncCall然后用线程池执行
* 返回Response后调用回调方法回调都是在子线程。
* =================================
* 他的巧妙的结构在于 ,链式的调用结构
* Response r = chain.proceed(request);
*
* Interceptor=>
* Response intercept(Chain chain){
* //处理Request
* Response r = chain.proceed(chain.request());
* //处理Response
* return r;
* }
*
* Chain=>中方法
* Response proceed(Request request){
* //这里主要遍历取出拦截器
* Response r = interceptors.get(index++).intercept(new Chain());
* return r;
* }
*
* ==============================
* 使用builder模式创建Request,OkHttpClient
* 使用工厂模式创建 EventListener
* 策略模式,设置拦截器
*/
private void requestOkHttpGet() {
new Thread(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void run() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
okhttp3.Request.Builder builder = new okhttp3.Request.Builder();
okhttp3.Request request = builder.url("http://www.google.com").build();
// 必须在这定义 // try-with-resources
try (okhttp3.Response response = okHttpClient.newCall(request).execute()) {
// try-with-resources
// 回调形式
// okHttpClient.newCall(request).enqueue(new Callback() {
// @Override
// public void onFailure(okhttp3.Call call, IOException e) {
//
// }
//
// @Override
// public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
//
// }
// });
// 注意这里是string()不是toString();
String s = response.body().string();
Log.i(TAG, "requestOkHttpGet: " + s);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
use of okhttp3.Dispatcher in project apollo-android by apollographql.
the class CacheHeadersTest method testDefaultHeadersReceived.
@Test
@SuppressWarnings("CheckReturnValue")
public void testDefaultHeadersReceived() throws Exception {
final AtomicBoolean hasHeader = new AtomicBoolean();
final NormalizedCache normalizedCache = new NormalizedCache() {
@Nullable
@Override
public Record loadRecord(@NonNull String key, @NonNull CacheHeaders cacheHeaders) {
hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE));
return null;
}
@Nonnull
@Override
public Set<String> merge(@NonNull Record record, @NonNull CacheHeaders cacheHeaders) {
hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE));
return emptySet();
}
@Override
public void clearAll() {
}
@Override
public boolean remove(@Nonnull CacheKey cacheKey) {
return false;
}
@Nonnull
@Override
protected Set<String> performMerge(@Nonnull Record apolloRecord, @Nonnull CacheHeaders cacheHeaders) {
return emptySet();
}
};
final NormalizedCacheFactory<NormalizedCache> cacheFactory = new NormalizedCacheFactory<NormalizedCache>() {
@Override
public NormalizedCache create(RecordFieldJsonAdapter recordFieldAdapter) {
return normalizedCache;
}
};
CacheHeaders cacheHeaders = CacheHeaders.builder().addHeader(ApolloCacheHeaders.DO_NOT_STORE, "true").build();
ApolloClient apolloClient = ApolloClient.builder().normalizedCache(cacheFactory, new IdFieldCacheKeyResolver()).serverUrl(server.url("/")).okHttpClient(new OkHttpClient.Builder().dispatcher(new Dispatcher(Utils.immediateExecutorService())).build()).dispatcher(Utils.immediateExecutor()).defaultCacheHeaders(cacheHeaders).build();
server.enqueue(mockResponse("HeroAndFriendsNameResponse.json"));
Rx2Apollo.from(apolloClient.query(new HeroAndFriendsNamesQuery(Input.fromNullable(Episode.NEWHOPE))).cacheHeaders(cacheHeaders)).test();
assertThat(hasHeader.get()).isTrue();
}
use of okhttp3.Dispatcher in project apollo-android by apollographql.
the class HttpCacheTest method setUp.
@Before
public void setUp() {
CustomTypeAdapter<Date> dateCustomTypeAdapter = new CustomTypeAdapter<Date>() {
@Override
public Date decode(CustomTypeValue value) {
try {
return DATE_FORMAT.parse(value.value.toString());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
@Override
public CustomTypeValue encode(Date value) {
return new CustomTypeValue.GraphQLString(DATE_FORMAT.format(value));
}
};
cacheStore = new MockHttpCacheStore();
cacheStore.delegate = new DiskLruHttpCacheStore(inMemoryFileSystem, new File("/cache/"), Integer.MAX_VALUE);
HttpCache cache = new ApolloHttpCache(cacheStore, null);
okHttpClient = new OkHttpClient.Builder().addInterceptor(new TrackingInterceptor()).addInterceptor(cache.interceptor()).dispatcher(new Dispatcher(Utils.immediateExecutorService())).readTimeout(2, TimeUnit.SECONDS).writeTimeout(2, TimeUnit.SECONDS).build();
apolloClient = ApolloClient.builder().serverUrl(server.url("/")).okHttpClient(okHttpClient).dispatcher(Utils.immediateExecutor()).addCustomTypeAdapter(CustomType.DATE, dateCustomTypeAdapter).httpCache(cache).build();
}
use of okhttp3.Dispatcher in project apollo-android by apollographql.
the class ApolloCancelCallTest method cancelCallAfterEnqueueNoCallback.
@Test
public void cancelCallAfterEnqueueNoCallback() throws Exception {
OkHttpClient okHttpClient = new OkHttpClient.Builder().dispatcher(new Dispatcher(Utils.immediateExecutorService())).build();
apolloClient = ApolloClient.builder().serverUrl(server.url("/")).okHttpClient(okHttpClient).httpCache(new ApolloHttpCache(cacheStore, null)).build();
server.enqueue(mockResponse("EpisodeHeroNameResponse.json"));
final ApolloCall<EpisodeHeroNameQuery.Data> call = apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(Episode.EMPIRE)));
final TestObserver<Response<EpisodeHeroNameQuery.Data>> test = Rx2Apollo.from(call).test();
call.cancel();
test.awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertNoValues().assertNotComplete();
}
use of okhttp3.Dispatcher in project apollo-android by apollographql.
the class ApolloCancelCallTest method setup.
@Before
public void setup() {
cacheStore = new MockHttpCacheStore();
OkHttpClient okHttpClient = new OkHttpClient.Builder().dispatcher(new Dispatcher(Utils.immediateExecutorService())).build();
apolloClient = ApolloClient.builder().serverUrl(server.url("/")).dispatcher(Utils.immediateExecutor()).okHttpClient(okHttpClient).httpCache(new ApolloHttpCache(cacheStore, null)).build();
}
Aggregations