Example usage for com.squareup.okhttp OkHttpClient networkInterceptors

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

Introduction

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

Prototype

List networkInterceptors

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

Click Source Link

Usage

From source file:keywhiz.client.ClientUtilsTest.java

License:Apache License

@Test
public void testSslOkHttpClientCreation() throws Exception {
    OkHttpClient sslClient = ClientUtils.sslOkHttpClient(config.getDevTrustStore(), ImmutableList.of());

    assertThat(sslClient.getFollowSslRedirects()).isFalse();
    assertThat(sslClient.getSslSocketFactory()).isNotNull();
    assertThat(sslClient.networkInterceptors()).isNotEmpty();

    assertThat(sslClient.getCookieHandler()).isNotNull();
    java.util.List<HttpCookie> cookieList = ((CookieManager) sslClient.getCookieHandler()).getCookieStore()
            .getCookies();/* www  . j  a va  2  s.c  o  m*/
    assertThat(cookieList).isEmpty();
}

From source file:keywhiz.client.ClientUtilsTest.java

License:Apache License

@Test
public void testSslOkHttpClientCreationWithCookies() throws Exception {
    OkHttpClient sslClient = ClientUtils.sslOkHttpClient(config.getDevTrustStore(), cookieList);

    assertThat(sslClient.getFollowSslRedirects()).isFalse();
    assertThat(sslClient.getCookieHandler()).isNotNull();
    assertThat(sslClient.getSslSocketFactory()).isNotNull();
    assertThat(sslClient.networkInterceptors()).isNotEmpty();

    java.util.List<HttpCookie> cookieList = ((CookieManager) sslClient.getCookieHandler()).getCookieStore()
            .getCookies();//from w  ww .  ja v a 2 s  .co m
    assertThat(cookieList).contains(xsrfCookie);
    assertThat(cookieList).contains(sessionCookie);
}

From source file:meteor.operations.Meteor.java

License:Apache License

/**
 * Opens a connection to the server over websocket
 *
 * @param isReconnect whether this is a re-connect attempt or not
 *///w  w w  .j  a v  a  2s  .c  o  m
public void openConnection(final boolean isReconnect) {

    if (isReconnect) {
        if (isConnected()) {
            connect(mSessionID);
            return;
        }
    }

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(1, TimeUnit.MINUTES);
    client.setReadTimeout(1, TimeUnit.MINUTES);
    client.setWriteTimeout(1, TimeUnit.MINUTES);
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    client.networkInterceptors().add(loggingInterceptor);

    Request request = new Request.Builder().url(mServerUri).build();
    WebSocketCall.create(client, request).enqueue(mWebSocketObserver);
}

From source file:org.mariotaku.twidere.util.net.NetworkUsageUtils.java

License:Open Source License

public static void initForHttpClient(Context context, OkHttpClient client) {
    final List<Interceptor> interceptors = client.networkInterceptors();
    interceptors.add(new NetworkUsageInterceptor(context));
}

From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java

License:Open Source License

public OAuthPasswordAuthenticator(final TwitterOAuth oauth,
        final LoginVerificationCallback loginVerificationCallback, final String userAgent) {
    final RestClient restClient = RestAPIFactory.getRestClient(oauth);
    this.oauth = oauth;
    this.client = (OkHttpRestClient) restClient.getRestClient();
    final OkHttpClient okhttp = client.getClient();
    okhttp.setCookieHandler(new CookieManager());
    okhttp.networkInterceptors().add(new Interceptor() {
        @Override/*from  ww  w .j a v  a  2 s  . com*/
        public Response intercept(Chain chain) throws IOException {
            final Response response = chain.proceed(chain.request());
            if (!response.isRedirect()) {
                return response;
            }
            final String location = response.header("Location");
            final Response.Builder builder = response.newBuilder();
            if (!TextUtils.isEmpty(location) && !endpoint.checkEndpoint(location)) {
                final HttpUrl originalLocation = HttpUrl
                        .get(URI.create("https://api.twitter.com/").resolve(location));
                final HttpUrl.Builder locationBuilder = HttpUrl.parse(endpoint.getUrl()).newBuilder();
                for (String pathSegments : originalLocation.pathSegments()) {
                    locationBuilder.addPathSegment(pathSegments);
                }
                for (int i = 0, j = originalLocation.querySize(); i < j; i++) {
                    final String name = originalLocation.queryParameterName(i);
                    final String value = originalLocation.queryParameterValue(i);
                    locationBuilder.addQueryParameter(name, value);
                }
                final String encodedFragment = originalLocation.encodedFragment();
                if (encodedFragment != null) {
                    locationBuilder.encodedFragment(encodedFragment);
                }
                final HttpUrl newLocation = locationBuilder.build();
                builder.header("Location", newLocation.toString());
            }
            return builder.build();
        }
    });
    this.endpoint = restClient.getEndpoint();
    this.loginVerificationCallback = loginVerificationCallback;
    this.userAgent = userAgent;
}

From source file:org.projectbuendia.client.net.VolleySingleton.java

License:Apache License

private VolleySingleton(Context context) {
    // Let Stetho inspect all our network requests.
    final OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new StethoInterceptor());

    // getApplicationContext() is key, it keeps you from leaking the
    // Activity or BroadcastReceiver if someone passes one in.
    mRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));
}

From source file:org.tecrash.crashreport.DropboxUploadingJob.java

License:Open Source License

@Override
public void onRun() throws Throwable {
    long last = Util.getLastEntryTimestamp(); // ??
    if (!Build.VERSION.INCREMENTAL.equals(incremental)) {
        // ??drpbox entry??
        long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
        if (bootTime > last) {
            last = bootTime;/*from ww w  . ja v  a2  s  . c  om*/
            Util.setLastEntryTimestamp(last);
        }
    }
    //        if (last >= timestamp) {
    //            logger.d("Cancelled as it was reported before!");
    //            return;
    //        }
    if (!Util.isEnabled()) {
        logger.d("Disabled so cancel it!");
        Util.setLastEntryTimestamp(last);
        return;
    }

    DropBoxManager dbm = (DropBoxManager) ReportApp.getInstance().getSystemService(Context.DROPBOX_SERVICE);
    List<ReportDatas.Entry> datas = new ArrayList<ReportDatas.Entry>();
    List<Long> timestamps = new ArrayList<Long>();
    List<String> tags = new ArrayList<String>();
    List<Long> entryTimestamps = new ArrayList<Long>();

    for (String tag : Util.getTags().keySet()) {
        DropBoxManager.Entry entry = dbm.getNextEntry(tag, last);
        while (entry != null) {
            ReportDatas.Entry data = convertToReportEntry(entry);
            if (data != null) {
                boolean found = false;
                for (ReportDatas.Entry d : datas) {
                    if (d.tag.equals(data.tag) && d.app.equals(data.app)) {
                        d.data.count += data.data.count;
                        if (d.data.count > 5)
                            d.data.count = 5;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    datas.add(data);
                    timestamps.add(last);
                    tags.add(tag);
                }
            }
            last = entry.getTimeMillis();
            entryTimestamps.add(last);
            entry = dbm.getNextEntry(tag, last);
        }
        //set back to last saved, for next tag
        last = Util.getLastEntryTimestamp();
    }

    IDropboxService service = getReportService(Util.getURL());

    // report dropbox entries
    ReportDatas.ReportResults results = service.report(Util.getKey(), Util.getUserAgent(),
            new ReportDatas(datas));

    //set the latest entry's timestamp as last
    if (!entryTimestamps.isEmpty()) {
        Collections.sort(entryTimestamps);
        last = entryTimestamps.get(entryTimestamps.size() - 1);
    }
    // save where to upload next time.
    Util.setLastEntryTimestamp(last);

    //check whether to report full dropbox entry content and log
    if (shouldReportDetail()) {
        for (int i = 0; i < results.data.length; i++) {
            ReportDatas.Result result = results.data[i];
            ReportDatas.Entry data = datas.get(i);
            if (result != null && result.dropbox_id != null && result.dropbox_id.length() > 0) {
                DropBoxManager.Entry entry = dbm.getNextEntry(tags.get(i), timestamps.get(i));
                // use okhttp to gzip content
                OkHttpClient client = new OkHttpClient();
                client.networkInterceptors().add(new GzipRequestInterceptor());
                RequestBody requestBody = new StreamRequestBody(entry.getInputStream());
                Request request = new Request.Builder()
                        .url(Util.getURL() + "/dropbox/" + result.dropbox_id + "/content")
                        .header("Authorization", Util.getKey()).post(requestBody).build();
                client.newCall(request).execute();
            }
        }
        IDropboxService uploadService = getReportService(Util.getUploadURL());
        for (int i = 0; i < results.data.length; i++) {
            ReportDatas.Result result = results.data[i];
            if (result != null && result.dropbox_id != null && result.dropbox_id.length() > 0) { // server received the data
                // upload attachment
                ReportDatas.Entry data = datas.get(i);
                if (data.data.log != null && data.data.log.length() > 0
                        && (data.data.log.endsWith(".gz") || data.data.log.endsWith(".zip"))) {
                    File file = new File(data.data.log);
                    if (file.exists()) {
                        uploadService.uploadAttachment(Util.getKey(), result.dropbox_id,
                                new TypedFile("application/zip", file));
                    }
                }
            }
        }
    }
    logger.d("** Total %d Dropbox entries added!", results.data.length);
}

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 ww  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:tw.bun.app_002.BunApiClient.java

License:Apache License

public static List<Word> getWords() {
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new StethoInterceptor());

    // Create a very simple REST adapter which points the Bun API endpoint.
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).setClient(new OkClient(client))
            .build();//  w  w  w. j a v a2 s  .  c  o  m

    // Create an instance of our Bun API interface.
    Bun bun = restAdapter.create(Bun.class);

    // Fetch and print a list of the words to this library.
    return bun.words();
}

From source file:tw.bun.app_002.GitHubClient.java

License:Apache License

public static List<Contributor> getContributors() {
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new StethoInterceptor());

    // Create a very simple REST adapter which points the GitHub API endpoint.
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).setClient(new OkClient(client))
            .build();/*from w  w w .ja  v a  2  s.c o  m*/

    // Create an instance of our GitHub API interface.
    GitHub github = restAdapter.create(GitHub.class);

    // Fetch and print a list of the contributors to this library.
    return github.contributors("2t10p", "Foundation-invoice");
}