LoginSignup
1
1

More than 1 year has passed since last update.

初めに

今回は、API通信のために必要なRetrofitとOkHttpの実装方法を紹介していこうと思います
ライブラリの準備自体は調べればいくらでも出てくるので簡潔になるように実装部分のみを記載していこうと思います

実装方法

    private val httpBuilder: OkHttpClient.Builder
        get() = if (BuildConfig.DEBUG) {
            OkHttpClient.Builder()
                .addInterceptor(
                    HttpLoggingInterceptor().apply {
                        level = HttpLoggingInterceptor.Level.BODY
                    }
                )
                .writeTimeout(writeTimeout.first, writeTimeout.second)
                .readTimeout(readTimeout.first, readTimeout.second)
        } else {
            OkHttpClient.Builder()
                .writeTimeout(writeTimeout.first, writeTimeout.second)
                .readTimeout(readTimeout.first, readTimeout.second)
        }

    @ExperimentalSerializationApi
    fun provide(): ApiClient {
        val contentType = "application/json".toMediaType()
        val format = Json { ignoreUnknownKeys = true }

        return Retrofit.Builder()
            .client(httpBuilder.build())
            .baseUrl(BuildConfig.API_ENDPOINT)
            .addConverterFactory(format.asConverterFactory(contentType))
            .build()
            .create(ApiClient::class.java)
    }

    companion object {
        private val writeTimeout = 30L to TimeUnit.SECONDS
        private val readTimeout = 30L to TimeUnit.SECONDS
    }

addInterceptorは発信要求と着信応答をログに記載するためのものです

上記のprovideメソッドをDagger Hilt等でDIすることで使用することができます

最後に

自分が初心者の頃にAPIの実装が右も左も分からないことが多かったので何かの役に立てれば幸いです

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1