Home > front end >  Get Retrofit annotation path for login purposes
Get Retrofit annotation path for login purposes

Time:06-14

I am using Retrofit with OkHttp. I like to add okhttp3.Interceptor to log the annotation path.

For example:

@GET("posts/{post_id}")
suspend fun getPost(@Path("post_id") postId: String): Response<Post>

Interceptor

class MyInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Chain): Response {
          // log the path here
    }
}

I like to log posts/{post_id} each time getPost is called. How can it be achieved?

CodePudding user response:

found the answer in the tags of the request

    fun extractPath(request: Request) = request.run {
        javaClass.getDeclaredField("tags").let {
            it.isAccessible = true
            @Suppress("UNCHECKED_CAST")
            it.get(this) as Map<Class<*>, Any>
        }
    }.run {
        values.first().run {
            javaClass.getDeclaredField("method").let {
                it.isAccessible = true
                (it.get(this) as Method).annotations[0]
            }
        }
    }.run {
        when (this) {
            is DELETE -> value
            is GET -> value
            is HEAD -> value
            is OPTIONS -> value
            is PATCH -> value
            is POST -> value
            is PUT -> value
            else -> null
        }
    }

CodePudding user response:

You may want to check out HttpLoggingInterceptor, for example here.

  • Related