Search in sources :

Example 31 with Interceptor

use of okhttp3.Interceptor in project Tusky by Vavassor.

the class BaseActivity method createMastodonAPI.

protected void createMastodonAPI() {
    mastodonApiDispatcher = new Dispatcher();
    Gson gson = new GsonBuilder().registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()).registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()).create();
    OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder builder = originalRequest.newBuilder();
            String accessToken = getAccessToken();
            if (accessToken != null) {
                builder.header("Authorization", String.format("Bearer %s", accessToken));
            }
            Request newRequest = builder.build();
            return chain.proceed(newRequest);
        }
    }).dispatcher(mastodonApiDispatcher).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(getBaseUrl()).client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build();
    mastodonAPI = retrofit.create(MastodonAPI.class);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) GsonBuilder(com.google.gson.GsonBuilder) SpannedTypeAdapter(com.keylesspalace.tusky.json.SpannedTypeAdapter) Request(okhttp3.Request) Gson(com.google.gson.Gson) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) StringWithEmojiTypeAdapter(com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter) MastodonAPI(com.keylesspalace.tusky.network.MastodonAPI) Interceptor(okhttp3.Interceptor) StringWithEmoji(com.keylesspalace.tusky.json.StringWithEmoji)

Example 32 with Interceptor

use of okhttp3.Interceptor in project cw-omnibus by commonsguy.

the class Downloader method onHandleIntent.

@Override
public void onHandleIntent(Intent i) {
    mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    try {
        String filename = i.getData().getLastPathSegment();
        NotificationCompat.Builder builder = buildForeground(filename);
        final Notification notif = builder.build();
        startForeground(FOREGROUND_ID, notif);
        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        root.mkdirs();
        File output = new File(root, filename);
        if (output.exists()) {
            output.delete();
        }
        final ProgressResponseBody.Listener progressListener = new ProgressResponseBody.Listener() {

            long lastUpdateTime = 0L;

            @Override
            public void onProgressChange(long bytesRead, long contentLength, boolean done) {
                long now = SystemClock.uptimeMillis();
                if (now - lastUpdateTime > 1000) {
                    notif.contentView.setProgressBar(android.R.id.progress, (int) contentLength, (int) bytesRead, false);
                    mgr.notify(FOREGROUND_ID, notif);
                    lastUpdateTime = now;
                }
            }
        };
        Interceptor nightTrain = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response original = chain.proceed(chain.request());
                Response.Builder b = original.newBuilder().body(new ProgressResponseBody(original.body(), progressListener));
                return (b.build());
            }
        };
        OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(nightTrain).build();
        Request request = new Request.Builder().url(i.getData().toString()).build();
        Response response = client.newCall(request).execute();
        String contentType = response.header("Content-type");
        BufferedSink sink = Okio.buffer(Okio.sink(new File(output.getPath())));
        sink.writeAll(response.body().source());
        sink.close();
        stopForeground(true);
        raiseNotification(contentType, output, null);
    } catch (IOException e2) {
        stopForeground(true);
        raiseNotification(null, null, e2);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Notification(android.app.Notification) Response(okhttp3.Response) NotificationCompat(android.support.v4.app.NotificationCompat) File(java.io.File) Interceptor(okhttp3.Interceptor)

Example 33 with Interceptor

use of okhttp3.Interceptor in project azure-sdk-for-java by Azure.

the class KeyVaultCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request().url();
            Map<String, String> challengeMap = cache.getCachedChallenge(url);
            if (challengeMap != null) {
                // Get the bearer token
                String credential = getAuthenticationCredentials(challengeMap);
                Request newRequest = chain.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
                return chain.proceed(newRequest);
            } else {
                // response
                return chain.proceed(chain.request());
            }
        }
    });
    // Caches the challenge for failed request and re-send the request with
    // access token.
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            // if challenge is not cached then extract and cache it
            String authenticateHeader = response.header(WWW_AUTHENTICATE);
            Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
            // Cache the challenge
            cache.addCachedChallenge(response.request().url(), challengeMap);
            // Get the bearer token from the callback by providing the
            // challenges
            String credential = getAuthenticationCredentials(challengeMap);
            if (credential == null) {
                return null;
            }
            // be cached anywhere in our code.
            return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
        }
    });
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) Map(java.util.Map) HashMap(java.util.HashMap) HttpUrl(okhttp3.HttpUrl) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 34 with Interceptor

use of okhttp3.Interceptor in project WordPress-Android by wordpress-mobile.

the class GravatarApi method createClient.

private static OkHttpClient createClient(final String accessToken) {
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    //// uncomment the following line to add logcat logging
    //httpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    // add oAuth token usage
    httpClientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Bearer " + accessToken).method(original.method(), original.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    return httpClientBuilder.build();
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 35 with Interceptor

use of okhttp3.Interceptor in project Retrofit-Android-Basic by basil2style.

the class ServiceGenerator method createService.

public static <S> S createService(Class<S> serviceClass, final String authToken) {
    if (authToken != null) {
        httpClient.interceptors().add(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder().header("Authorization", authToken).method(original.method(), original.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }
    OkHttpClient client = httpClient.build();
    Retrofit retrofit = builder.client(client).build();
    return retrofit.create(serviceClass);
}
Also used : Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Aggregations

IOException (java.io.IOException)35 Interceptor (okhttp3.Interceptor)33 MockResponse (okhttp3.mockwebserver.MockResponse)29 Request (okhttp3.Request)26 Test (org.junit.Test)25 Response (okhttp3.Response)24 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)24 OkHttpClient (okhttp3.OkHttpClient)20 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)10 File (java.io.File)8 Provides (dagger.Provides)6 Singleton (javax.inject.Singleton)6 Cache (okhttp3.Cache)4 Retrofit (retrofit2.Retrofit)4 InterruptedIOException (java.io.InterruptedIOException)3 Call (okhttp3.Call)3 HttpUrl (okhttp3.HttpUrl)3 NonNull (android.support.annotation.NonNull)2 ANResponse (com.androidnetworking.common.ANResponse)2 ResponseProgressBody (com.androidnetworking.internal.ResponseProgressBody)2