From ce9fcf4ac83ad317d9f3f458318742f518d4cd7f Mon Sep 17 00:00:00 2001 From: Alexander Fink Date: Tue, 2 Oct 2018 00:29:23 +0200 Subject: [PATCH] Add network interception for okhttp2 and okhttp3 --- app/build.gradle | 2 + .../cispa/artist/codelib/CodeLib.java | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/app/build.gradle b/app/build.gradle index e524afa..f6b4123 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -33,4 +33,6 @@ dependencies { api fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.facebook.stetho:stetho:1.5.0' implementation 'com.facebook.stetho:stetho-js-rhino:1.4.2' + implementation 'com.facebook.stetho:stetho-okhttp:1.5.0' + implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1' } diff --git a/app/src/main/java/saarland/cispa/artist/codelib/CodeLib.java b/app/src/main/java/saarland/cispa/artist/codelib/CodeLib.java index 1df2935..115162f 100644 --- a/app/src/main/java/saarland/cispa/artist/codelib/CodeLib.java +++ b/app/src/main/java/saarland/cispa/artist/codelib/CodeLib.java @@ -23,12 +23,18 @@ package saarland.cispa.artist.codelib; import android.content.Context; +import android.util.ArraySet; import android.util.Log; import com.facebook.stetho.Stetho; +import com.facebook.stetho.okhttp.StethoInterceptor; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import okhttp3.OkHttpClient.Builder; +import com.squareup.okhttp.OkHttpClient; + public class CodeLib { @interface Inject { @@ -74,4 +80,39 @@ public void initStetho(Object obj) { } } + + private final Set okhttp2blacklist = new ArraySet<>(); + + @Inject + @SuppressWarnings("unused") + public void okhttp2interceptor(Object obj) { + // blacklist required to prevent infinite loop as the method is injected into OkHttpClient.networkInterceptors() + if (obj != null && obj instanceof OkHttpClient) { + synchronized (okhttp2blacklist) { + if (!okhttp2blacklist.contains(obj)) { + try { + okhttp2blacklist.add(obj); + ((OkHttpClient) obj).networkInterceptors().add(new StethoInterceptor()); + Log.w(TAG, "Injected OkHttp2 interceptor"); + } catch (RuntimeException e) { + okhttp2blacklist.remove(obj); + Log.w(TAG, e); + } + } + } + } + } + + @Inject + @SuppressWarnings("unused") + public void okhttp3interceptor(Object obj){ + try { + ((Builder) obj).addNetworkInterceptor(new com.facebook.stetho.okhttp3.StethoInterceptor()); + Log.w(TAG, "Injected OkHttp3 Interceptor"); + } catch (RuntimeException e) { + Log.w(TAG, e); + } + } + + } \ No newline at end of file