Search code examples
androidandroid-networkingfirebase-performance

Android: How to capture App's Network Traffic Programmatically?


I'm currently working on a library that enables QA or Developers debug network traffic in their app, we currently use OKHttp and I know how to create an interceptor and dispatch all request data to the lib. such that Developers or QA can view such data (Payload/URL/Size/Response Codes/Duration...etc), however I want to create a more generic solution that listens to HTTP traffic or even TCP traffic then take it from there, however I couldn't find a starting point, I know that this is possible since Firebase Performance is doing it, but still I couldn't find an API or anyway to listen to such traffic.

I hope that someone from Google's Firebase Performance Team shares some info about how they do it if it's not a trade-secret :)

I came across this solution: https://github.com/cyruliu/Sensitive_API_Monitor/blob/master/app/src/main/java/com/android/reverse/apimonitor/NetWorkHook.java However it looks kinda bad with reflection, I hope to find a better way.


Solution

  • The short answer: It's not possible without proxying the whole device.

    For OkHttp3 specifically I wrote a lib here: https://github.com/shehabic/sherlock that implements an interceptor that creates a new session every time your open your app and captures network requests, you can also have multiple session, it adds a floating icon that helps you access sessions and requests' history as well as some export capabilities, additionally it adds a secondary launcher icon that you can use to access the captures requests without interrupting the app's process.

    Regarding Firebase Performance, all the magic is actually in the Firebase-Perf Gradle plugin; to simplify it, it scans through the project's code and replaces direct calls to OkHttpClient to be be proxied through their own FirebaseOkHttpClient and from there they get all the details even for https request as they become the http client.

    I hope that this saves someone some time in the future.