AndroidのJavaでRetrofit2のログを取る方法。
build.gradleでは各ライブラリのバージョンを以下のように設定している。
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
}
ログを取るには、HttpLoggingInterceptorを使用する。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
取得するログのレベルを設定する。
interceptor.level(HttpLoggingInterceptor.Level.BODY);
設定できるログのレベルは以下の通り。
- NONE ログを取らない
- BASIC リクエストとレスポンス
- HEADERS リクエストとレスポンスとそれぞれのヘッダー
- BODY リクエストとレスポンスとそれぞれのヘッダーと本文
HttpLoggingInterceptorを設定したOkHttpClientを作成する。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
RetrofitにOkHttpClientを設定する。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HOST)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
全体のコードは次のようになる。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
if (BuildConfig.DEBUG) {
interceptor.level(HttpLoggingInterceptor.Level.BODY);
} else {
interceptor.level(HttpLoggingInterceptor.Level.NONE);
}
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HOST)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();