Search in sources :

Example 61 with Dispatcher

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();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) StringRequest(com.android.volley.toolbox.StringRequest) Request(com.android.volley.Request) IOException(java.io.IOException)

Example 62 with Dispatcher

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();
}
Also used : Nonnull(javax.annotation.Nonnull) Dispatcher(okhttp3.Dispatcher) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RecordFieldJsonAdapter(com.apollographql.apollo.cache.normalized.RecordFieldJsonAdapter) ApolloCacheHeaders(com.apollographql.apollo.cache.ApolloCacheHeaders) CacheHeaders(com.apollographql.apollo.cache.CacheHeaders) HeroAndFriendsNamesQuery(com.apollographql.apollo.integration.normalizer.HeroAndFriendsNamesQuery) NormalizedCache(com.apollographql.apollo.cache.normalized.NormalizedCache) NonNull(android.support.annotation.NonNull) NormalizedCacheFactory(com.apollographql.apollo.cache.normalized.NormalizedCacheFactory) Record(com.apollographql.apollo.cache.normalized.Record) CacheKey(com.apollographql.apollo.cache.normalized.CacheKey) Test(org.junit.Test)

Example 63 with Dispatcher

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();
}
Also used : ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) OkHttpClient(okhttp3.OkHttpClient) ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) HttpCache(com.apollographql.apollo.api.cache.http.HttpCache) Dispatcher(okhttp3.Dispatcher) Date(java.util.Date) CustomTypeAdapter(com.apollographql.apollo.response.CustomTypeAdapter) CustomTypeValue(com.apollographql.apollo.response.CustomTypeValue) DiskLruHttpCacheStore(com.apollographql.apollo.cache.http.DiskLruHttpCacheStore) ParseException(java.text.ParseException) File(java.io.File) Before(org.junit.Before)

Example 64 with Dispatcher

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();
}
Also used : Response(com.apollographql.apollo.api.Response) MockResponse(okhttp3.mockwebserver.MockResponse) ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) OkHttpClient(okhttp3.OkHttpClient) EpisodeHeroNameQuery(com.apollographql.apollo.integration.normalizer.EpisodeHeroNameQuery) Dispatcher(okhttp3.Dispatcher) Test(org.junit.Test)

Example 65 with Dispatcher

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();
}
Also used : ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher) Before(org.junit.Before)

Aggregations

Dispatcher (okhttp3.Dispatcher)40 OkHttpClient (okhttp3.OkHttpClient)34 MockResponse (okhttp3.mockwebserver.MockResponse)27 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 Dispatcher (okhttp3.mockwebserver.Dispatcher)24 IOException (java.io.IOException)17 Before (org.junit.Before)14 Test (org.junit.Test)13 Call (okhttp3.Call)11 MockWebServer (okhttp3.mockwebserver.MockWebServer)11 LruNormalizedCacheFactory (com.apollographql.apollo.cache.normalized.lru.LruNormalizedCacheFactory)10 ArrayList (java.util.ArrayList)8 Request (okhttp3.Request)8 Response (okhttp3.Response)8 ResponseBody (okhttp3.ResponseBody)7 Gson (com.google.gson.Gson)5 Interceptor (okhttp3.Interceptor)5 CloudantClient (com.cloudant.client.api.CloudantClient)4 RefineTest (com.google.refine.RefineTest)4 DataExtensionConfig (com.google.refine.model.recon.ReconciledDataExtensionJob.DataExtensionConfig)4