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:org.wildfly.kubernetes.configmap.ConfigMapOperations.java

License:Open Source License

/**
 * @param args the command line arguments
 */// w w w .  j a  v a  2 s . c  o m
public static void main(String[] args) {
    try {
        final OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        Map<String, String> labels = new HashMap<>();
        labels.put("component", "wildfly");
        Path file = new File(
                "/home/ehsavoie/dev/wildfly/core/dist/target/wildfly-core-2.1.0.CR3-SNAPSHOT/standalone/configuration/standalone.xml")
                        .toPath();
        String name = "test";
        String namespace = "default";
        ConfigMapOperations ops = new ConfigMapOperations();
        if (ops.configMapExists(client, namespace, name)) {
            ops.deleteConfigMap(client, namespace, name);
        }
        ops.createConfigMap(client, namespace, name, labels, Collections.singleton(file));
        ops.createConfigMap(client, namespace, name, labels, Collections.singleton(file));

        labels.put("status", "experimental");
        ops.updateConfigMap(client, namespace, name, labels, Collections.singleton(file));
        ops.configMapExists(client, namespace, name);
        //            ops.deleteConfigMap(client, namespace, name);
    } catch (IOException ex) {
        Logger.getLogger(ConfigMapOperations.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:pedroscott.com.popularmoviesapp.rest.RestClientPublic.java

License:Apache License

private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);
    client.networkInterceptors().add(new Interceptor() {
        @Override/*from   w w w .  j av  a2  s. com*/
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl url = request.httpUrl().newBuilder().addQueryParameter("api_key", key).build();
            request = request.newBuilder().url(url).build();
            return chain.proceed(request);
        }
    });
    client.networkInterceptors().add(new StethoInterceptor());
    return client;
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override//from ww  w  .  jav  a2  s .  co m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client)
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
                    return new Converter<ResponseBody, String>() {
                        @Override
                        public String convert(ResponseBody value) throws IOException {
                            try {
                                return value.string();
                            } catch (IOException e) {
                                // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                                throw new RuntimeException("wrapper", e);
                            }
                        }
                    };
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi"));

    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}

From source file:retrofit.MagnetRestAdapter.java

License:Apache License

private MagnetRestAdapter(OkHttpClient client, BaseUrl baseUrl, List<Converter.Factory> converterFactories,
        /*List<CallAdapter.Factory> adapterFactories,*/ Executor callbackExecutor) {
    Log.d(TAG, "MagnetRestAdapter is created");
    this.client = client;
    this.baseUrl = baseUrl;
    this.converterFactories = converterFactories;
    //this.adapterFactories = adapterFactories;
    this.requestManager = new RequestManager(client);
    CallAdapter.Factory adapterFactory = new MagnetCallAdapter.Factory(this, requestManager);
    this.adapterFactories = Arrays.asList(adapterFactory);
    this.callbackExecutor = callbackExecutor;

    this.requestInterceptor = new RequestInterceptor(this, requestManager);
    client.interceptors().add(requestInterceptor);

    client.setAuthenticator(new MaxRestAuthenticator());
}

From source file:retrofit2.CallTest.java

License:Apache License

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override/*  w w w . j av a 2s .c  om*/
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client)
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                        Retrofit retrofit) {
                    return new Converter<ResponseBody, String>() {
                        @Override
                        public String convert(ResponseBody value) throws IOException {
                            try {
                                return value.string();
                            } catch (IOException e) {
                                // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                                throw new RuntimeException("wrapper", e);
                            }
                        }
                    };
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi"));

    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}

From source file:saulmm.avengers.model.rest.RestRepository.java

License:Mozilla Public License

@Inject
public RestRepository() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new MarvelSigningIterceptor(publicKey, privateKey));

    Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<List<Character>>() {
    }.getType(), new MarvelResultsCharacterDeserialiser()).registerTypeAdapter(new TypeToken<List<Comic>>() {
    }.getType(), new MarvelResultsComicsDeserialiser()).create();

    Retrofit marvelApiAdapter = new Retrofit.Builder().baseUrl(MarvelApi.END_POINT)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();

    mMarvelApi = marvelApiAdapter.create(MarvelApi.class);
}

From source file:saulmm.avengers.rest.RestDataSource.java

License:Mozilla Public License

@Inject
public RestDataSource(MarvelAuthorizer marvelAuthorizer) {
    OkHttpClient client = new OkHttpClient();

    MarvelSigningIterceptor signingIterceptor = new MarvelSigningIterceptor(marvelAuthorizer.getApiClient(),
            marvelAuthorizer.getApiSecret());

    HttpLoggingInterceptor logginInterceptor = new HttpLoggingInterceptor();
    logginInterceptor.setLevel(Level.BODY);

    client.interceptors().add(signingIterceptor);
    client.interceptors().add(logginInterceptor);

    Gson customGsonInstance = new GsonBuilder().registerTypeAdapter(new TypeToken<List<MarvelCharacter>>() {
    }.getType(), new MarvelResultsDeserializer<MarvelCharacter>())

            .registerTypeAdapter(new TypeToken<List<CollectionItem>>() {
            }.getType(), new MarvelResultsDeserializer<CollectionItem>())

            .create();//  w  w  w.  j av a2 s.  co  m

    Retrofit marvelApiAdapter = new Retrofit.Builder().baseUrl(END_POINT)
            .addConverterFactory(GsonConverterFactory.create(customGsonInstance))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();

    mMarvelApi = marvelApiAdapter.create(MarvelApi.class);
}

From source file:syncthing.api.SyncthingApiLongpollModule.java

License:Open Source License

@Provides
@SessionScope/*from  ww w .j  a  v a  2s  .co  m*/
@Named("longpoll")
public SyncthingApi provideSyncthingApi(Gson gson, OkHttpClient okClient, SyncthingApiConfig config) {
    OkHttpClient client = okClient.clone();
    client.setConnectTimeout(LONGPOLL_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(LONGPOLL_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setSslSocketFactory(SyncthingSSLSocketFactory.create(config.getCACert()));
    client.setHostnameVerifier(new NullHostNameVerifier());
    client.interceptors().add(new SyncthingApiInterceptor(config));
    Retrofit.Builder b = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(client).baseUrl(config.getBaseUrl());
    if (BuildConfig.DEBUG) {
        b.validateEagerly();
    }
    return b.build().create(SyncthingApi.class);
}

From source file:syncthing.api.SyncthingApiModule.java

License:Open Source License

@Provides
@SessionScope/*from ww  w . j ava 2s.  c om*/
public SyncthingApi provideSyncthingApi(Gson gson, OkHttpClient okClient, SyncthingApiConfig config) {
    OkHttpClient client = okClient.clone();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setSslSocketFactory(SyncthingSSLSocketFactory.create(config.getCACert()));
    client.setHostnameVerifier(new NullHostNameVerifier());
    client.interceptors().add(new SyncthingApiInterceptor(config));
    Retrofit.Builder b = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(client).baseUrl(config.getBaseUrl());
    if (BuildConfig.DEBUG) {
        b.validateEagerly();
    }
    return b.build().create(SyncthingApi.class);
}