Search in sources :

Example 26 with Dispatcher

use of mockwebserver3.Dispatcher in project AndLang by wugemu.

the class HttpU method newOkHttpClient.

public OkHttpClient newOkHttpClient() {
    HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
    logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    if (openDns) {
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).addNetworkInterceptor(// 添加网络请求日志
        logInterceptor).dns(new HttpDns()).build();
    } else if (openLog) {
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).addNetworkInterceptor(// 添加网络请求日志
        logInterceptor).build();
    } else if (BaseLangUtil.isHaveSDPer()) {
        // 开启本地存储权限后使用缓存机制
        // 新建一个cache,指定目录为外部目录下的okhttp_cache目录,大小为100M
        Cache cache = new Cache(PicSelUtil.getCacheDir(), 100 * 1024 * 1024);
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).cache(// 缓存设置
        cache).addInterceptor(// 请求网络拦截
        new RequestCacheI()).build();
    } else {
        // 新建一个cache,指定目录为外部目录下的okhttp_cache目录,大小为100M
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).build();
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache)

Example 27 with Dispatcher

use of mockwebserver3.Dispatcher in project apps-android-wikipedia by wikimedia.

the class MockWebServerTest method setUp.

@Before
public void setUp() throws Throwable {
    OkHttpClient.Builder builder = OkHttpConnectionFactory.getClient().newBuilder();
    okHttpClient = builder.dispatcher(new Dispatcher(new ImmediateExecutorService())).build();
    server.setUp();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher) Before(org.junit.Before)

Example 28 with Dispatcher

use of mockwebserver3.Dispatcher in project sonarlint-core by SonarSource.

the class MockWebServerExtension method beforeEach.

@Override
public void beforeEach(ExtensionContext context) throws Exception {
    server = new MockWebServer();
    responsesByPath.clear();
    final Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (responsesByPath.containsKey(request.getPath())) {
                return responsesByPath.get(request.getPath());
            }
            return new MockResponse().setResponseCode(404);
        }
    };
    server.setDispatcher(dispatcher);
    server.start();
}
Also used : RecordedRequest(mockwebserver3.RecordedRequest) MockResponse(mockwebserver3.MockResponse) MockWebServer(mockwebserver3.MockWebServer) Dispatcher(mockwebserver3.Dispatcher)

Example 29 with Dispatcher

use of mockwebserver3.Dispatcher in project kork by spinnaker.

the class RawOkHttpClientFactory method create.

/**
 * Returns a basic client which can be further customized for other needs in the {@link
 * OkHttpClientProvider} implementations. (eg: SSL setup, name verifier etc)
 */
public OkHttpClient create(OkHttpClientConfigurationProperties okHttpClientConfigurationProperties, List<Interceptor> interceptors, HttpTracing httpTracing) {
    Dispatcher dispatcher = zipkinHttpTracingDispatcher(httpTracing);
    dispatcher.setMaxRequests(okHttpClientConfigurationProperties.getMaxRequests());
    dispatcher.setMaxRequestsPerHost(okHttpClientConfigurationProperties.getMaxRequestsPerHost());
    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder().connectTimeout(okHttpClientConfigurationProperties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS).readTimeout(okHttpClientConfigurationProperties.getReadTimeoutMs(), TimeUnit.MILLISECONDS).retryOnConnectionFailure(okHttpClientConfigurationProperties.getRetryOnConnectionFailure()).dispatcher(dispatcher).addNetworkInterceptor(zipkinTracingInterceptor(httpTracing)).connectionPool(new ConnectionPool(okHttpClientConfigurationProperties.getConnectionPool().getMaxIdleConnections(), okHttpClientConfigurationProperties.getConnectionPool().getKeepAliveDurationMs(), TimeUnit.MILLISECONDS));
    if (interceptors != null) {
        interceptors.forEach(okHttpClientBuilder::addInterceptor);
    }
    return okHttpClientBuilder.build();
}
Also used : ConnectionPool(okhttp3.ConnectionPool) OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher)

Example 30 with Dispatcher

use of mockwebserver3.Dispatcher in project autorest-clientruntime-for-java by Azure.

the class ConnectionPoolTests method canUseOkHttpThreadPool.

// Simulates a server with response latency of 1 second. A connection pool
// size 2 should only send 2 requests per second.
@Test
public void canUseOkHttpThreadPool() throws Exception {
    RestClient restClient = new RestClient.Builder().withBaseUrl("https://microsoft.com").withSerializerAdapter(new JacksonAdapter()).withResponseBuilderFactory(new Factory()).withDispatcher(new Dispatcher(Executors.newFixedThreadPool(2))).useHttpClientThreadPool(true).withInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
            return new Response.Builder().request(chain.request()).code(200).message("OK").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
        }
    }).build();
    final Service service = restClient.retrofit().create(Service.class);
    final CountDownLatch latch = new CountDownLatch(1);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Observable.range(1, 4).flatMap(new Func1<Integer, Observable<?>>() {

        @Override
        public Observable<?> call(Integer integer) {
            return service.getAsync().subscribeOn(Schedulers.io());
        }
    }).doOnCompleted(new Action0() {

        @Override
        public void call() {
            latch.countDown();
        }
    }).subscribe();
    latch.await();
    stopWatch.stop();
    Assert.assertTrue(stopWatch.getTime() > 2000);
}
Also used : Action0(rx.functions.Action0) JacksonAdapter(com.microsoft.rest.serializer.JacksonAdapter) Factory(com.microsoft.rest.ServiceResponseBuilder.Factory) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) Observable(rx.Observable) StopWatch(org.apache.commons.lang3.time.StopWatch) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Aggregations

Dispatcher (okhttp3.Dispatcher)43 OkHttpClient (okhttp3.OkHttpClient)28 Before (org.junit.Before)14 LruNormalizedCacheFactory (com.apollographql.apollo.cache.normalized.lru.LruNormalizedCacheFactory)10 IOException (java.io.IOException)9 Interceptor (okhttp3.Interceptor)7 Test (org.junit.Test)7 Call (okhttp3.Call)6 RecordedRequest (mockwebserver3.RecordedRequest)5 ApolloHttpCache (com.apollographql.apollo.cache.http.ApolloHttpCache)3 CustomTypeValue (com.apollographql.apollo.response.CustomTypeValue)3 ParseException (java.text.ParseException)3 MockResponse (mockwebserver3.MockResponse)3 ConnectionPool (okhttp3.ConnectionPool)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 Buffer (okio.Buffer)3 NonNull (android.support.annotation.NonNull)2 IdFieldCacheKeyResolver (com.apollographql.apollo.IdFieldCacheKeyResolver)2 Response (com.apollographql.apollo.api.Response)2