0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Retrofit / OkHttp APIコール時にヘッダ、パラメータ追加

Posted at

Retrofit2 / OkHttp3 でAPI通信機能作成時にヘッダやパラメータを追加する場合のメモ

よくあるこんなの

fun builderHttpClient(): OkHttpClient =
    OkHttpClient.Builder().apply {
        when (BuildConfig.BUILD_TYPE) {
            "debug", "staging" -> {
                val logging = HttpLoggingInterceptor()
                logging.level = HttpLoggingInterceptor.Level.BODY
                addInterceptor(logging)
            }
            else -> {
                // nop
            }
        }

        addInterceptor(createInterceptor())
        authenticator(認証用Authenticator())
        connectTimeout(Environment.TIME_INTERVAL, TimeUnit.SECONDS)
        readTimeout(Environment.TIME_INTERVAL, TimeUnit.SECONDS)
    }.build()

createInterceptor() の部分で追加

private fun createInterceptor(): Interceptor {
    return object : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            // パラメータ追加
            val url: HttpUrl = chain.request().url.newBuilder()
                    .addQueryParameter(PARAMETER_NAME, PARAMETER_VALUE).build()

            // 認証トークン、OS Version などをヘッダに追加
            val request = chain.request().newBuilder()
                .header("Authorization", AuthorizeDataStore().accessToken ?: "")
                .header(
                    "x-app-version",
                    "${BuildConfig.VERSION_MAJOR}.${BuildConfig.VERSION_MINOR}.${BuildConfig.VERSION_PATCH}"
                )
                .header("x-os", "android")
                .header("x-os-version", Build.VERSION.RELEASE)
                .url(url)
                .build()
            return chain.proceed(request)
        }
    }
}

認証やトラッキングなどのパラメータ、ヘッダ追加を共通化

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?