在登录后添加头部拦截器 – Retrofit

huangapple go评论141阅读模式
英文:

Add header interceptor after login - Retrofit

问题

我在过去的一些日子里遇到了一个问题,我知道如何设置一个头部拦截器,问题是,我如何在登录后设置一个头部拦截器,因为我的流程是:

首先进行不带身份验证的登录,只使用用户名和密码。

然后服务器返回Bearer令牌。

我该如何自动设置头部验证,而不是在每次调用Retrofit时手动添加它?有没有办法实现这个?

我需要使用相同的Retrofit实例吗?

英文:

I'm having an issue from some days, I know how to set a header interceptor, the thing is, how do I set a header interceptor only after the login because my flow is :

Login without auth just user and password

Then server returns the Bearer token

How do I set the header authentication automatically instead of adding it manually on each call of retrofit? Is there any way?
Do I have to use the same instance of Retrofit?

答案1

得分: 1

你可以通过创建自定义的拦截器来实现,以下是代码示例:

class AuthorizationInterceptor(var context: Context) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request: Request = chain.request()
        val sessionId = "Your Session Id"

        if (tempSessionId != null) {
            request = request.newBuilder()
                .addHeader("Authorization", "Bearer $tempSessionId").build()
        }
       return chain.proceed(request)
    }
}

然后按照以下方式添加这个拦截器:

class RetrofitInstance(var context: Context) {

    private val BASE_URL = APIVersionConstants.BASE_URL

    private val builder = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(makeOkHttpClient()) 

    private fun makeOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(AuthorizationInterceptor(context)) // <----HERE
            .build()
    }

    private val retrofit = builder.build()

    fun <T> buildService(serviceType: Class<T>): T {
        return retrofit.create(serviceType)
    }
}

完成了。

英文:

You can do it by making your custom interceptor, below is the code

 class AuthorizationInterceptor(var context: Context) : Interceptor {

     override fun intercept(chain: Interceptor.Chain): Response {
        var request: Request = chain.request()
        val sessionId = &quot;Your Session Id&quot;

        if (tempSessionId != null) {
            request = request.newBuilder()
                .addHeader(&quot;Authorization&quot;, &quot;Bearer $tempSessionId&quot;).build()
        }
       return chain.proceed(request)
     }
}

And then add this Interceptor by following way

class RetrofitInstance(var context: Context) {

    private val BASE_URL = APIVersionConstants.BASE_URL


    private val builder = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(makeOkHttpClient()) 


    private fun makeOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(AuthorizationInterceptor(context)) //&lt;----HERE
            .build()
    }

    private val retrofit = builder.build()

    fun &lt;T&gt; buildService(serviceType: Class&lt;T&gt;): T {
        return retrofit.create(serviceType)
    }


}

It's done

huangapple
  • 本文由 发表于 2020年3月16日 06:22:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/60698260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定