Adding header to all request with Retrofit 2

前端 未结 10 1394
北荒
北荒 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()
                //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() {
                        override fun onSuccess(response: Response) {
                            super.onSuccess(response)
                            //handle response
                        }
                    }).run(this)
    

    For more information see the documentation

提交回复
热议问题