Android Retrofit2 Interceptor request Header 추가 | 레트로핏2 인터셉터 헤더 추가

Android Retrofit2 Interceptor request Header 추가 변경 & response 처리

val retrofit: TrendNewsService = Retrofit.Builder()
    .baseUrl(basedUrl)
    .addConverterFactory(GsonConverterFactory.create(
        GsonBuilder().setLenient().create()
    ))
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .client(
        OkHttpClient.Builder()
            .addInterceptor(
                HttpLoggingInterceptor().apply {
                    this.level = HttpLoggingInterceptor.Level.BODY
                })
            .addInterceptor(CustomInterceptor()) // 만들어야 할 custom Interceptor
            .build()
    )
    .build()
    .create(TrendNewsService::class.java)
class CustomInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        
        // Request Header 추가
        val request = chain.request()
        request.newBuilder().addHeader("content-type", "charset=UTF-8").build()
        request.newBuilder().addHeader("what-you-want-header", "data").build()
        
        // Response 값 처리
        val response = chain.proceed(request)

        // 데이터의 정상 여부에 따라 결과를 변환하여 처리
        return if (response.code == 200) {
            val bodyString = response.body?.string()?.replace(")]}',", "")?.trim() ?: ""

            val body =
                convertedBody.toResponseBody("application/json; charset=utf-8".toMediaTypeOrNull())
            response.newBuilder().body(body).build()
        } else {
            response
        }
    }

}

결론



Related Posts