Search in sources :

Example 26 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 27 with Interceptor

use of okhttp3.Interceptor in project ride-read-android by Ride-Read.

the class RetrofitUtils method addHeaderInterceptor.

/**
     * 设置头
     */
private static Interceptor addHeaderInterceptor() {
    Interceptor headerInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder requestBuilder = originalRequest.newBuilder().header("AppType", "TPOS").header("Accept", "application/json").method(originalRequest.method(), originalRequest.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    };
    return headerInterceptor;
}
Also used : Request(okhttp3.Request) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Example 28 with Interceptor

use of okhttp3.Interceptor in project ride-read-android by Ride-Read.

the class RetrofitUtils method addQueryParameterInterceptor.

/**
     * 设置公共参数
     */
private static Interceptor addQueryParameterInterceptor() {
    Interceptor addQueryParameterInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request request;
            HttpUrl modifiedUrl = originalRequest.url().newBuilder().addQueryParameter("", Integer.toString(UserUtils.getUid())).addQueryParameter("token", UserUtils.getToken()).build();
            ;
            if (0 != UserUtils.getUid()) {
                modifiedUrl = originalRequest.url().newBuilder().addQueryParameter("uid", Integer.toString(UserUtils.getUid())).addQueryParameter("token", UserUtils.getToken()).build();
            }
            request = originalRequest.newBuilder().url(modifiedUrl).build();
            return chain.proceed(request);
        }
    };
    return addQueryParameterInterceptor;
}
Also used : Request(okhttp3.Request) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpUrl(okhttp3.HttpUrl)

Example 29 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 30 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)

Aggregations

IOException (java.io.IOException)37 Interceptor (okhttp3.Interceptor)36 Request (okhttp3.Request)29 MockResponse (okhttp3.mockwebserver.MockResponse)29 Response (okhttp3.Response)25 Test (org.junit.Test)25 OkHttpClient (okhttp3.OkHttpClient)24 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)24 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)9 File (java.io.File)8 Retrofit (retrofit2.Retrofit)8 Provides (dagger.Provides)6 Singleton (javax.inject.Singleton)6 Cache (okhttp3.Cache)5 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)3 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