Example usage for com.squareup.okhttp OkHttpClient interceptors

List of usage examples for com.squareup.okhttp OkHttpClient interceptors

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient interceptors.

Prototype

List interceptors

To view the source code for com.squareup.okhttp OkHttpClient interceptors.

Click Source Link

Usage

From source file:com.btkelly.gnag.api.GitHubApi.java

License:Apache License

private GitHubApi(final GnagPluginExtension gnagPluginExtension) {
    this.gnagPluginExtension = gnagPluginExtension;

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.interceptors().add(new AuthInterceptor(gnagPluginExtension));
    okHttpClient.interceptors().add(new LoggingInterceptor());

    String baseUrl = "https://api.github.com/repos/" + gnagPluginExtension.getGitHubRepoName() + "/";

    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);

    Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient)
            .addConverterFactory(gsonConverterFactory).build();

    gitHubApiClient = retrofit.create(GitHubApiClient.class);
}

From source file:com.camnter.easygank.gank.EasyGank.java

License:Open Source License

private EasyGank() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);

    /*//from w  w  w .j  a  va 2s.com
     * ??
     */
    if (EasyApplication.getInstance().log) {
        okHttpClient.interceptors().add(chain -> {
            Response response = chain.proceed(chain.request());
            com.orhanobut.logger.Logger.d(chain.request().urlString());
            return response;
        });
    }

    Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(EasyApplication.getInstance().gson))
            .client(okHttpClient).build();
    this.gankService = retrofit.create(GankService.class);
}

From source file:com.carlospinan.demoretrofit2.helpers.API.java

License:Open Source License

public APIService getRetrofitService() {
    if (service == null) {
        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new LoggingInterceptor());
        Retrofit retrofit = new Retrofit.Builder().baseUrl(ENDPOINT_URL)
                .addConverterFactory(GsonConverterFactory.create()).client(client).build();
        service = retrofit.create(APIService.class);
    }/*  ww w  .  j  a v a 2s  .c  om*/
    return service;
}

From source file:com.dreamdigitizers.androidsoundcloudapi.core.Api.java

private Api(final String pClientId, final String pOauthToken) {
    OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.interceptors().add(new Interceptor() {
        @Override/*from  w w  w . ja  v a  2s . com*/
        public Response intercept(Chain pChain) throws IOException {
            Request request = pChain.request();
            HttpUrl.Builder builder = request.httpUrl().newBuilder();
            builder.addQueryParameter("client_id", pClientId);
            if (!TextUtils.isEmpty(pOauthToken)) {
                builder.addQueryParameter("oauth_token", pOauthToken);
            }
            HttpUrl httpUrl = builder.build();
            Log.d(Api.TAG, httpUrl.url().toString());
            request = request.newBuilder().url(httpUrl).build();
            Response response = pChain.proceed(request);
            String bodyString = response.body().string();
            response = response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString)).build();
            Log.d(Api.TAG, bodyString);
            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(IApi.API_URL__BASE).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    this.mApi = retrofit.create(IApi.class);
}

From source file:com.example.app.di.modules.ApiModule.java

License:Apache License

@Provides
@Singleton// w w  w .java 2s.  co  m
@Named("noCache")
OkHttpClient provideNoCacheOkHttpClient(HttpLoggingInterceptor loggingInterceptor,
        @Named("userAgent") String userAgentValue) {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(loggingInterceptor);
    client.networkInterceptors().add(new UserAgentInterceptor(userAgentValue));
    client.networkInterceptors().add(new StethoInterceptor());
    return client;
}

From source file:com.example.app.di.modules.ApiModule.java

License:Apache License

@Provides
@Singleton//from  w  w w  .j  a  va 2s .c o  m
@Named("cache")
OkHttpClient provideOkHttpClient(Cache cache, HttpLoggingInterceptor loggingInterceptor,
        @Named("userAgent") String userAgentValue) {
    OkHttpClient client = new OkHttpClient();
    client.setCache(cache);
    client.interceptors().add(loggingInterceptor);
    client.networkInterceptors().add(new UserAgentInterceptor(userAgentValue));
    client.networkInterceptors().add(new CacheResponseInterceptor());
    client.networkInterceptors().add(new StethoInterceptor());
    return client;
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private static OkHttpClient buildDefaultClient() {
    OkHttpClient c = new OkHttpClient();

    c.setFollowRedirects(true);/*from  ww w  . j a va  2 s .  c o  m*/
    c.setFollowSslRedirects(true);
    c.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setHostnameVerifier(buildHostnameVerifier());
    c.setSslSocketFactory(buildSSLSocketFactory());
    c.interceptors().add(new GzipInterceptor());

    return c;
}

From source file:com.heroiclabs.sdk.android.HttpClient.java

License:Apache License

/** {@inheritDoc} */
public <T> Deferred<Response<T>> execute(final @NonNull Request<T> request) {
    final Deferred<Response<T>> deferred = new Deferred<>();

    // Select the host, implicitly only allow HTTPS.
    HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("https")
            .host(getServer(request.getDestination()));

    // Encode and add the path elements.
    for (final String p : getPath(request.getRequestType(), request.getIdentifiers())) {
        urlBuilder = urlBuilder.addPathSegment(p);
    }/*from   w  ww . jav  a  2  s .c  om*/

    // Encode and add the query parameters, toString() values as we go.
    for (final Map.Entry<String, ?> e : request.getParameters().entrySet()) {
        urlBuilder = urlBuilder.addQueryParameter(e.getKey(), e.getValue().toString());
    }
    final HttpUrl url = urlBuilder.build();

    final String token = request.getSession() == null ? "" : request.getSession().getToken();
    final String authorization = "Basic " + ByteString.of((apiKey + ":" + token).getBytes()).base64();

    final String contentType = "application/json";
    final String body = getBody(request.getRequestType(), request.getEntity());

    // Construct the HTTP request.
    final com.squareup.okhttp.Request httpRequest = new com.squareup.okhttp.Request.Builder().url(url)
            .method(getMethod(request.getRequestType()),
                    body == null ? null : RequestBody.create(MediaType.parse(contentType), body))
            .header("User-Agent", USER_AGENT).header("Content-Type", contentType).header("Accept", contentType)
            .header("Authorization", authorization).build();

    // Prepare a HTTP client instance to execute against.
    final OkHttpClient client = this.client.clone();

    // Interceptors fire in the order they're declared.
    // Note: Compress first, so we don't re-compress for retried requests.
    if (this.compressRequests) {
        client.interceptors().add(GzipRequestInterceptor.INSTANCE);
    }
    final int maxAttempts = request.getMaxAttempts() < 1 ? this.maxAttempts : request.getMaxAttempts();
    client.interceptors().add(new RetryInterceptor(maxAttempts));

    // Log the outgoing request.
    if (log.isDebugEnabled()) {
        log.debug("Request: Method{" + httpRequest.method() + "} URL{" + httpRequest.urlString() + "} Headers{"
                + httpRequest.headers().toString() + "} Body{" + body + "}");
    }

    // Send the request and retrieve a response.
    client.newCall(httpRequest).enqueue(new Callback() {
        @Override
        public void onFailure(final com.squareup.okhttp.Request httpRequest, final IOException e) {
            // Log the request failure reason.
            if (log.isDebugEnabled()) {
                log.debug("Request Failed", e);
            }

            deferred.callback(new ErrorResponse(e.getMessage(), e, request));
        }

        @Override
        public void onResponse(final @NonNull com.squareup.okhttp.Response httpResponse) throws IOException {
            switch (httpResponse.code()) {
            // Good response with body.
            case HttpURLConnection.HTTP_OK:
                final String responseBody = httpResponse.body().string();

                // Log the incoming response.
                if (log.isDebugEnabled()) {
                    log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{"
                            + httpResponse.request().urlString() + "} Code{" + httpResponse.code()
                            + "} Message{" + httpResponse.message() + "} Headers:{"
                            + httpResponse.headers().toString() + "} Body{" + responseBody + "}");
                }

                final T entity = codec.deserialize(responseBody, request.getResponseType());
                deferred.callback(new SuccessResponse<>(request, httpResponse.code(), responseBody, entity));
                break;

            // Good response, no body.
            case HttpURLConnection.HTTP_NO_CONTENT:
            case HttpURLConnection.HTTP_CREATED:
                // Log the incoming response.
                if (log.isDebugEnabled()) {
                    log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{"
                            + httpResponse.request().urlString() + "} Code{" + httpResponse.code()
                            + "} Message{" + httpResponse.message() + "} Headers:{"
                            + httpResponse.headers().toString() + "}");
                }

                deferred.callback(new SuccessResponse<>(request, httpResponse.code(), null, null));
                break;

            // Error response.
            default:
                final String errorBody = httpResponse.body().string();

                // Log the incoming response.
                if (log.isDebugEnabled()) {
                    log.debug("Response Error: Method{" + httpResponse.request().method() + "} URL{"
                            + httpResponse.request().urlString() + "} Code{" + httpResponse.code()
                            + "} Message{" + httpResponse.message() + "} Headers:{"
                            + httpResponse.headers().toString() + "} Body{" + errorBody + "}");
                }

                @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
                final ErrorDetails error = errorBody.isEmpty()
                        ? new ErrorDetails(httpResponse.code(),
                                httpResponse.message() == null ? "unknown" : httpResponse.message(), null)
                        : codec.deserialize(errorBody, ErrorDetails.class);
                deferred.callback(new ErrorResponse(error.getMessage(), error, request));
            }

            // Indicate that application-layer response processing is complete.
            httpResponse.body().close();
        }
    });

    return deferred;
}

From source file:com.heske.alexandria.api.AlexandriaApplication.java

License:Apache License

private void setupRestAdapter() {
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    mRetrofit = new Retrofit.Builder().baseUrl("https://www.googleapis.com/books/")
            .addConverterFactory(JacksonConverterFactory.create()).client(client).build();

    mApiService = mRetrofit.create(BookApiService.class);
}

From source file:com.liferay.mobile.screens.context.LiferayServerContext.java

License:Open Source License

public static OkHttpClient getOkHttpClientNoCache() {
    OkHttpClient noCacheClient = getOkHttpClient().clone();
    noCacheClient.interceptors().add(new Interceptor() {
        @Override//ww  w.j a v a 2s.c o  m
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            Request newRequest = originalRequest.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();

            return chain.proceed(newRequest);
        }
    });

    return noCacheClient;
}