AmSabba
AmSabba

Reputation: 67

adding a header to all requests in the retrofit factory?

i have this factory which is used for all outgoing requests in the app, is it possible to add a header here (app version) instead of on all requests? other examples ive seen all seem to use a different syntax for the factory, i think its an older one but i am not sure

object RetrofitFactory {

    val makeRetrofitService: RetrofitService by lazy {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build()

        Retrofit.Builder()
            .baseUrl("${CustomURI.BaseWebsite}/")
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
            .client(client)
            .build().create(RetrofitService::class.java)
    }

}

Upvotes: 0

Views: 613

Answers (2)

Aleksey Kislyakov
Aleksey Kislyakov

Reputation: 64

You can add multiple interceptors to your OkHttpClient. It should something like this: This is your logging interceptor:

    val interceptor = HttpLoggingInterceptor()
    interceptor.level = HttpLoggingInterceptor.Level.BODY

This is a header one

OkHttpClient.Builder().apply {
        addInterceptor { chain ->
            val request = chain.request()
            val builder = request
                .newBuilder()
                .header("SOME", "SOME")
                .method(request.method(), request.body())
            val mutatedRequest = builder.build()
            val response = chain.proceed(mutatedRequest)
            response
        }
        addInterceptor(interceptor) // this is your http logging
    }.build()

Change SOME and SOME with your preferred values.

Upvotes: 2

Nour Eldien Mohamed
Nour Eldien Mohamed

Reputation: 961

I found this solution , you can add this by using Interceptor

in this link How to define a Header to all request using Retrofit?

RequestInterceptor requestInterceptor = new RequestInterceptor() {
  @Override
  public void intercept(RequestFacade request) {
    request.addHeader("User-Agent", "Retrofit-Sample-App");
  }
};

RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setRequestInterceptor(requestInterceptor)
.build();

Upvotes: 0

Related Questions