Search in sources :

Example 1 with OkHttpClient

use of okhttp3.OkHttpClient in project MovieGuide by esoxjem.

the class NetworkModule method provideOkHttpClient.

@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return new okhttp3.OkHttpClient.Builder().connectTimeout(CONNECT_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS).addInterceptor(loggingInterceptor).build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 2 with OkHttpClient

use of okhttp3.OkHttpClient in project buck by facebook.

the class ArtifactCaches method createHttpArtifactCache.

private static ArtifactCache createHttpArtifactCache(HttpCacheEntry cacheDescription, final String hostToReportToRemote, final BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem, ListeningExecutorService httpWriteExecutorService, ArtifactCacheBuckConfig config, NetworkCacheFactory factory, boolean distributedBuildModeEnabled) {
    // Setup the default client to use.
    OkHttpClient.Builder storeClientBuilder = new OkHttpClient.Builder();
    storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder().addHeader("X-BuckCache-User", stripNonAscii(System.getProperty("user.name", "<unknown>"))).addHeader("X-BuckCache-Host", stripNonAscii(hostToReportToRemote)).build()));
    int timeoutSeconds = cacheDescription.getTimeoutSeconds();
    setTimeouts(storeClientBuilder, timeoutSeconds);
    storeClientBuilder.connectionPool(new ConnectionPool(/* maxIdleConnections */
    (int) config.getThreadPoolSize(), /* keepAliveDurationMs */
    config.getThreadPoolKeepAliveDurationMillis(), TimeUnit.MILLISECONDS));
    // The artifact cache effectively only connects to a single host at a time. We should allow as
    // many concurrent connections to that host as we allow threads.
    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequestsPerHost((int) config.getThreadPoolSize());
    storeClientBuilder.dispatcher(dispatcher);
    final ImmutableMap<String, String> readHeaders = cacheDescription.getReadHeaders();
    final ImmutableMap<String, String> writeHeaders = cacheDescription.getWriteHeaders();
    // If write headers are specified, add them to every default client request.
    if (!writeHeaders.isEmpty()) {
        storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), writeHeaders).build()));
    }
    OkHttpClient storeClient = storeClientBuilder.build();
    // For fetches, use a client with a read timeout.
    OkHttpClient.Builder fetchClientBuilder = storeClient.newBuilder();
    setTimeouts(fetchClientBuilder, timeoutSeconds);
    // If read headers are specified, add them to every read client request.
    if (!readHeaders.isEmpty()) {
        fetchClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), readHeaders).build()));
    }
    fetchClientBuilder.networkInterceptors().add((chain -> {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), buckEventBus)).build();
    }));
    OkHttpClient fetchClient = fetchClientBuilder.build();
    HttpService fetchService;
    HttpService storeService;
    switch(config.getLoadBalancingType()) {
        case CLIENT_SLB:
            HttpLoadBalancer clientSideSlb = config.getSlbConfig().createClientSideSlb(new DefaultClock(), buckEventBus, new CommandThreadFactory("ArtifactCaches.HttpLoadBalancer", SLB_THREAD_PRIORITY));
            fetchService = new RetryingHttpService(buckEventBus, new LoadBalancedService(clientSideSlb, fetchClient, buckEventBus), config.getMaxFetchRetries());
            storeService = new LoadBalancedService(clientSideSlb, storeClient, buckEventBus);
            break;
        case SINGLE_SERVER:
            URI url = cacheDescription.getUrl();
            fetchService = new SingleUriService(url, fetchClient);
            storeService = new SingleUriService(url, storeClient);
            break;
        default:
            throw new IllegalArgumentException("Unknown HttpLoadBalancer type: " + config.getLoadBalancingType());
    }
    String cacheName = cacheDescription.getName().map(input -> "http-" + input).orElse("http");
    boolean doStore = cacheDescription.getCacheReadMode().isDoStore();
    return factory.newInstance(NetworkCacheArgs.builder().setThriftEndpointPath(config.getHybridThriftEndpoint()).setCacheName(cacheName).setRepository(config.getRepository()).setScheduleType(config.getScheduleType()).setFetchClient(fetchService).setStoreClient(storeService).setDoStore(doStore).setProjectFilesystem(projectFilesystem).setBuckEventBus(buckEventBus).setHttpWriteExecutorService(httpWriteExecutorService).setErrorTextTemplate(cacheDescription.getErrorMessageFormat()).setDistributedBuildModeEnabled(distributedBuildModeEnabled).build());
}
Also used : ConnectionPool(okhttp3.ConnectionPool) BuckEventBus(com.facebook.buck.event.BuckEventBus) Okio(okio.Okio) Source(okio.Source) BytesReceivedEvent(com.facebook.buck.event.NetworkEvent.BytesReceivedEvent) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) Dispatcher(okhttp3.Dispatcher) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) CommonGroups(com.facebook.buck.randomizedtrial.CommonGroups) BuckConfig(com.facebook.buck.cli.BuckConfig) ImmutableList(com.google.common.collect.ImmutableList) DefaultClock(com.facebook.buck.timing.DefaultClock) Map(java.util.Map) ForwardingSource(okio.ForwardingSource) Response(okhttp3.Response) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer) URI(java.net.URI) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Logger(com.facebook.buck.log.Logger) Request(okhttp3.Request) Buffer(okio.Buffer) SingleUriService(com.facebook.buck.slb.SingleUriService) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CharMatcher(com.google.common.base.CharMatcher) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) TimeUnit(java.util.concurrent.TimeUnit) BufferedSource(okio.BufferedSource) OkHttpClient(okhttp3.OkHttpClient) Optional(java.util.Optional) ConnectionPool(okhttp3.ConnectionPool) AsyncCloseable(com.facebook.buck.util.AsyncCloseable) RandomizedTrial(com.facebook.buck.randomizedtrial.RandomizedTrial) DirCacheExperimentEvent(com.facebook.buck.event.DirCacheExperimentEvent) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) OkHttpClient(okhttp3.OkHttpClient) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) Dispatcher(okhttp3.Dispatcher) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) URI(java.net.URI) Response(okhttp3.Response) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) HttpService(com.facebook.buck.slb.HttpService) DefaultClock(com.facebook.buck.timing.DefaultClock) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) SingleUriService(com.facebook.buck.slb.SingleUriService) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer)

Example 3 with OkHttpClient

use of okhttp3.OkHttpClient in project feign by OpenFeign.

the class OkHttpClient method execute.

@Override
public feign.Response execute(feign.Request input, feign.Request.Options options) throws IOException {
    okhttp3.OkHttpClient requestScoped;
    if (delegate.connectTimeoutMillis() != options.connectTimeoutMillis() || delegate.readTimeoutMillis() != options.readTimeoutMillis()) {
        requestScoped = delegate.newBuilder().connectTimeout(options.connectTimeoutMillis(), TimeUnit.MILLISECONDS).readTimeout(options.readTimeoutMillis(), TimeUnit.MILLISECONDS).build();
    } else {
        requestScoped = delegate;
    }
    Request request = toOkHttpRequest(input);
    Response response = requestScoped.newCall(request).execute();
    return toFeignResponse(response).toBuilder().request(input).build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

Example 4 with OkHttpClient

use of okhttp3.OkHttpClient in project SeriesGuide by UweTrottmann.

the class HttpClientModule method provideOkHttpClient.

/**
     * Returns this apps {@link OkHttpClient} with enabled response cache. Should be used with API
     * calls.
     */
@Provides
@Singleton
OkHttpClient provideOkHttpClient(SgApp app, Cache cache) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    builder.readTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    builder.addInterceptor(new SgTmdbInterceptor());
    builder.addNetworkInterceptor(new SgTheTvdbInterceptor(app));
    builder.addNetworkInterceptor(new SgTraktInterceptor(app));
    builder.authenticator(new AllApisAuthenticator(app));
    builder.cache(cache);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SgTmdbInterceptor(com.battlelancer.seriesguide.tmdbapi.SgTmdbInterceptor) SgTraktInterceptor(com.battlelancer.seriesguide.traktapi.SgTraktInterceptor) SgTheTvdbInterceptor(com.battlelancer.seriesguide.thetvdbapi.SgTheTvdbInterceptor) AllApisAuthenticator(com.battlelancer.seriesguide.util.AllApisAuthenticator) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 5 with OkHttpClient

use of okhttp3.OkHttpClient in project lottie-android by airbnb.

the class AnimationFragment method loadUrl.

private void loadUrl(String url) {
    Request request;
    try {
        request = new Request.Builder().url(url).build();
    } catch (IllegalArgumentException e) {
        onLoadError();
        return;
    }
    if (client == null) {
        client = new OkHttpClient();
    }
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            onLoadError();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) {
                onLoadError();
            }
            try {
                JSONObject json = new JSONObject(response.body().string());
                LottieComposition.Factory.fromJson(getResources(), json, new OnCompositionLoadedListener() {

                    @Override
                    public void onCompositionLoaded(LottieComposition composition) {
                        setComposition(composition, "Network Animation");
                    }
                });
            } catch (JSONException e) {
                onLoadError();
            }
        }
    });
}
Also used : Call(okhttp3.Call) OnCompositionLoadedListener(com.airbnb.lottie.OnCompositionLoadedListener) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) LottieComposition(com.airbnb.lottie.LottieComposition)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)631 Request (okhttp3.Request)359 Response (okhttp3.Response)302 IOException (java.io.IOException)196 Test (org.junit.Test)155 Call (okhttp3.Call)111 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)67 Retrofit (retrofit2.Retrofit)65 File (java.io.File)56 Interceptor (okhttp3.Interceptor)45 RequestBody (okhttp3.RequestBody)39 ResponseBody (okhttp3.ResponseBody)38 Cache (okhttp3.Cache)36 Gson (com.google.gson.Gson)33 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)33 Headers (okhttp3.Headers)33 Callback (okhttp3.Callback)32 GsonBuilder (com.google.gson.GsonBuilder)29 JSONObject (org.json.JSONObject)28 Provides (dagger.Provides)27