API通信まわりの実装をする際は、ログを見れたほうが作業が捗りますよね。
今回はokhttp3を使ってログを出力する方法をご紹介します。
- macOS: 10.14.1
- Android Studio: 3.4
- kotlin: 1.3.21
手順
build.gradleへの追加
logging-interceptor
を追加します。
app/build.gradle
def okhttp_version = '3.11.0'
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version" // ログ出力に必要
OkHttpClientの設定
ランタイムなどの設定と一緒に、.addInterceptor...
の箇所を追加します。
init {
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
// ログを出力させる設定
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.build()
}
手順は以上です。
出力してみる

※もし手順通りに設定したにもかかわらずログが出力されない場合は、通信以前のところ(例えばインターネット通信の許可をしていないとか)でつまずいている可能性があるので確認してみてください。