0

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)
    }

}
AmSabba
  • 67
  • 5
  • You can create an OkHttp interceptor that adds headers, then add that interceptor to your `OkHttpClient.Builder`. – CommonsWare Jun 28 '20 at 16:17

2 Answers2

1

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.

0

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();