The easy way to create a Gson model from an OkHttp/Retrofit request in an Android project
Thousands of developers around the world use the OkHttp client for the network and the Gson for model parsing.
Each of them spends a lot of time on Gson models creation. But why don’t we automate this process yet? Why do we need to do this monotonic work if we can use this time for interesting tasks?
Relax, now you can do it in one click!
The OkHttp Profiler plugin for an Android Studio and an IntellijIDEA can show http/https request details in the tool window. You can explore request/response headers, you can see the JSON response as a tree, as a plain text etc. And you can create a Java/Kotlin model. Just click right mouse button on a root element of the tree (or any other), choose Java or Kotlin, and select a folder for a new file in the project (for example project/app/src/main/java/com/example/data).
Boom! The model is ready!
To activate, just add the library to the android gradle file (build.gradle) in your module (application/app/build.gradle)
dependencies {
//……………
implementation 'com.itkacher.okhttpprofiler:okhttpprofiler:1.0.4'
}
Sync the gradle project to apply the changes and set an interceptor to okhttp client by adding the following code to okhttp client or retrofit:
For raw OkHttp client:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
builder.addInterceptor(new OkHttpProfilerInterceptor());
}
OkHttpClient client = builder.build();
For Retrofit:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
builder.addInterceptor(new OkHttpProfilerInterceptor());
}
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
……
.client(client)
.build();
We recommend to enable it only for debug build (BuildConfig.DEBUG), but you can remove it if you want to see requests also in release app.
Your app is ready, but you still need to install the plugin.
Now open Android Studio preferences, select the “Plugins” tab, and type “OkHttp Profiler” into a search field. If there is a “No plugins found” message, press “Search in repositories” .
You will see a list with the “OkHttp Profiler” plugin, so press the install button and wait through installation, then restart Android Studio.
Now you should be able to see http & https requests directly in Android Studio!
Open an “OkHttp Profiler” tool window in the right bottom corner and run your project with all changes.
You will see detailed data for each request from the OkHttp library, as soon, they will be sent to the network! Quite simple, right? That’s it.