Adding header to all request with Retrofit 2

前端 未结 10 1351
北荒
北荒 2020-11-29 17:46

Retrofit 2\'s documentation says:

Headers that need to be added to every request can be specified using an OkHttp interceptor.

I

相关标签:
10条回答
  • 2020-11-29 18:17

    RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code.

    Add headers in your application class like this :

    class Application : Application() {
    
        override fun onCreate() {
        super.onCreate()
    
            retrofitClient = RetrofitClient.instance
                        //api url
                    .setBaseUrl("https://reqres.in/")
                        //you can set multiple urls
            //                .setUrl("example","http://ngrok.io/api/")
                        //set timeouts
                    .setConnectionTimeout(4)
                    .setReadingTimeout(15)
                        //enable cache
                    .enableCaching(this)
                        //add Headers
                    .addHeader("Content-Type", "application/json")
                    .addHeader("client", "android")
                    .addHeader("language", Locale.getDefault().language)
                    .addHeader("os", android.os.Build.VERSION.RELEASE)
                }
    
            companion object {
            lateinit var retrofitClient: RetrofitClient
    
            }
        }  
    

    And then make your call:

    retrofitClient.Get<GetResponseModel>()
                //set path
                .setPath("api/users/2")
                //set url params Key-Value or HashMap
                .setUrlParams("KEY","Value")
                // you can add header here
                .addHeaders("key","value")
                .setResponseHandler(GetResponseModel::class.java,
                    object : ResponseHandler<GetResponseModel>() {
                        override fun onSuccess(response: Response<GetResponseModel>) {
                            super.onSuccess(response)
                            //handle response
                        }
                    }).run(this)
    

    For more information see the documentation

    0 讨论(0)
  • 2020-11-29 18:18

    For Logging your request and response you need an interceptor and also for setting the header you need an interceptor, Here's the solution for adding both the interceptor at once using retrofit 2.1

     public OkHttpClient getHeader(final String authorizationValue ) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient okClient = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .addNetworkInterceptor(
                            new Interceptor() {
                                @Override
                                public Response intercept(Interceptor.Chain chain) throws IOException {
                                    Request request = null;
                                    if (authorizationValue != null) {
                                        Log.d("--Authorization-- ", authorizationValue);
    
                                        Request original = chain.request();
                                        // Request customization: add request headers
                                        Request.Builder requestBuilder = original.newBuilder()
                                                .addHeader("Authorization", authorizationValue);
    
                                        request = requestBuilder.build();
                                    }
                                    return chain.proceed(request);
                                }
                            })
                    .build();
            return okClient;
    
        }
    

    Now in your retrofit object add this header in the client

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(getHeader(authorizationValue))
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    
    0 讨论(0)
  • 2020-11-29 18:22

    Use this Retrofit Client

    class RetrofitClient2(context: Context) : OkHttpClient() {
    
        private var mContext:Context = context
        private var retrofit: Retrofit? = null
    
        val client: Retrofit?
            get() {
                val logging = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
    
                val client = OkHttpClient.Builder()
                        .connectTimeout(Constants.TIME_OUT, TimeUnit.SECONDS)
                        .readTimeout(Constants.TIME_OUT, TimeUnit.SECONDS)
                        .writeTimeout(Constants.TIME_OUT, TimeUnit.SECONDS)
                client.addInterceptor(logging)
                client.interceptors().add(AddCookiesInterceptor(mContext))
    
                val gson = GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create()
                if (retrofit == null) {
    
                    retrofit = Retrofit.Builder()
                            .baseUrl(Constants.URL)
                            .addConverterFactory(GsonConverterFactory.create(gson))
                            .client(client.build())
                            .build()
                }
                return retrofit
            }
    }
    

    I'm passing the JWT along with every request. Please don't mind the variable names, it's a bit confusing.

    class AddCookiesInterceptor(context: Context) : Interceptor {
        val mContext: Context = context
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder = chain.request().newBuilder()
            val preferences = CookieStore().getCookies(mContext)
            if (preferences != null) {
                for (cookie in preferences!!) {
                    builder.addHeader("Authorization", cookie)
                }
            }
            return chain.proceed(builder.build())
        }
    }
    
    0 讨论(0)
  • 2020-11-29 18:25

    Kotlin version would be

    fun getHeaderInterceptor():Interceptor{
        return object : Interceptor {
            @Throws(IOException::class)
            override fun intercept(chain: Interceptor.Chain): Response {
                val request =
                chain.request().newBuilder()
                        .header(Headers.KEY_AUTHORIZATION, "Bearer.....")
                        .build()
                return chain.proceed(request)
            }
        }
    }
    
    
    private fun createOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
                .apply {
                    if(BuildConfig.DEBUG){
                        this.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
                    }
                }
                .addInterceptor(getHeaderInterceptor())
                .build()
    }
    
    0 讨论(0)
提交回复
热议问题