Retrofit Android - add header to existing Retrofit object - android

Is there a way to add a header to a Retrofit object after it has been created ?
I create a Retrofit object using the Retrofit Builder and then at a later point need to add a certain header to it. The reason for adding it here is that this particular header needs to be added with all requests and its value is dynamic. I would like to avoid having to add this header to every network call separately. Here is how I create it:
Retrofit.Builder builder = new Retrofit.Builder()
.client(client)
.baseUrl(String.format(baseUrl, environmentExtension) + "/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
builder.build();
I would like to add the header to this existing object.

To add header to all the requests, you can intercept calls using Interceptor and tweak the request to add header. This has to be done while building OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(chain -> chain.proceed(chain.request().newBuilder()
.addHeader("key","value").build()));
OkHttpClient client = builder.build();//use this client in retrofit

The best way could be creating an Interceptor and adding it through the OkHttpClient's builder. You can achieve it as following;
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val requestBuilder = originalRequest.newBuilder()
.header("Key", "Value")
val request = requestBuilder.build()
return chain.proceed(request)
}
}
val httpClient = OkHttpClient.Builder().apply {
connectTimeout(60, SECONDS)
readTimeout(60, SECONDS)
writeTimeout(60, SECONDS)
interceptors().add(headerInterceptor)
}.build()
You can introduce above interceptor to Retrofit's object as following;
Retrofit.Builder().apply {
baseUrl(BuildConfig.BASE_URL)
addConverterFactory(Json.asConverterFactory(MEDIA_TYPE_DEFAULT.toMediaType()))
client(httpClient)
}.build()

Related

Android HTTP Headers with API

What are headers used for if I want to do a post request & response ?
How is it possible to "save" token there ?
I can't find any good explanation about it.
you can use Retrofit to call api and store token into shared preferences and add common headers to OkhttpClient
val prefs = Prefs.getInstance();
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor { chain ->
val original = chain.request()
val request = original.newBuilder()
.header("Authorization", prefs.token)
.header("Accept", "application/json")
.method(original.method, original.body)
.build()
chain.proceed(request)
}
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
httpClient.addInterceptor(interceptor)
val client = httpClient.build()
and make Retrofit object like this
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(
GsonConverterFactory.create(
GsonBuilder().setPrettyPrinting().create()
)
)
.client(client).build()

what is retrofit interceptor , can we have multiple?

I can not understand the retrofit interceptors ,
private val OkHttpClient by lazy {
okhttp3.OkHttpClient.Builder()
.addInterceptor {
onOnIntercept(it)
}
.addInterceptor(LoggingInterceptor())
.addInterceptor(getInterceptor404())
.callTimeout(10, TimeUnit.MILLISECONDS)
// .addInterceptor(TimeoutInterceptor())
.build()
}
and what do these lines do, and If I have, multiple does the speed down?
val response: Response = chain.proceed(chain.request())
return chain.proceed(chain.request())
In Android sometimes you need to add a couple of parameters, like headers, to make a successful request, this is normal behavior from all the Android Apps when you are using Retrofit, you can do it in multiple ways
For example, you can add parameters directly to your request interface using the annotation Headers and putting a plain String, like this:
#Headers("Content-Type:application/json; charset=UTF-8")
#GET("yourwebsite/{someParam}/login")
fun logout(#Path("someParam") someParam: String?): Observable<LoginResponseViewModel>
Another solution is to send the Headers as a parameter to your interface function, using an annotation Header and sending a parameter, this gives you the possibility to have a custom parameter that you can manage from every request:
#Headers("Content-Type:application/json; charset=UTF-8")
#GET("yourwebsite/{someParam}/login")
fun logout(#Header(UUID.randomUUID().toString()) authToken: String?, #Path("someParam") someParam: String?): Observable<LoginResponseViewModel>**
Interceptor
A couple of people using Dagger probably will go for an Interceptor, you can have two types of interceptor:
The first one is using an interceptor directly in your Singleton, this will not give you versatility, but it will solve your problem faster, in this example, you can go for the chain object, get the request of the Retrofit call, get a new Builder and then add the Headers.
#Provides
#Singleton
fun getUnsafeOkHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val builder = OkHttpClient.Builder()
builder.addInterceptor(interceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.addInterceptor { chain ->
val newRequest = chain.request().newBuilder()
.addHeader("Authorization", UUID.randomUUID().toString())
.build()
chain.proceed(newRequest)
}
}
Yes, you can use multiple interceptors. When you do a request calling interface method using retrofit, your request go to the interceptor and then continue. In the interceptor you can rewrite or retry request. For example, you could add the access token in all request and refresh the token if is necessary, add the headers, another bodies, etc. When you received a response from api, the interceptor intercept the response too. But please, read the documentation to understand how it works. Have a nice coding!

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

How to add header to retrofit response in Android

In my application i want get data from server and for this i should add some header such as Accept and Content_Type .
For connect to server i used Retrofit library.
For set headers i use okHttp client and i write below codes, but not set header to api response!
My Client codes:
class ApiClient() {
private val apiServices: ApiServices
init {
//Gson
val gson = GsonBuilder()
.setLenient()
.create()
//Http log
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level =
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
//Http Builder
val clientBuilder = OkHttpClient.Builder()
clientBuilder.interceptors().add(loggingInterceptor)
clientBuilder.addInterceptor { chain ->
val request = chain.request()
request.newBuilder().addHeader(
CONTENT_TYPE,
APPLICATION_JSON
).build()
chain.proceed(request)
}
clientBuilder.addInterceptor { chain ->
val request = chain.request()
request.newBuilder().addHeader(
ACCEPT,
APPLICATION_JSON
).build()
chain.proceed(request)
}
//Http client
val client = clientBuilder
.readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.callTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
//Retrofit
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL + BASE_URP_PREFIX)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
//Init mapApiServices
apiServices = retrofit.create(ApiServices::class.java)
}
companion object {
private var apiClient: ApiClient? = null
fun getInstance(): ApiClient =
apiClient ?: synchronized(this) {
apiClient
?: ApiClient().also {
apiClient = it
}
}
}
}
How can i fix it?
The first option to add a static header is to define the header and respective value for your API method as an annotation. The header gets automatically added by Retrofit for every request using this method. The annotation can be either key-value-pair as one string or as a list of strings.
The example above shows the key-value-definition for the static header:
Further, you can pass multiple key-value-strings as a list encapsulated in curly brackets {} to the #Headers annotation.
How you can pass multiple key-value-strings as a list encapsulated in curly brackets:
A more customizable approach are dynamic headers. A dynamic header is passed like a parameter to the method. The provided parameter value gets mapped by Retrofit before executing the request.
Define dynamic headers where you might pass different values for each request:
Happy Coding!! 😎

Android Retrofit update HTTP client configuration

We have a case where we may have to update the public keys when using Certificate Pinning with OKHttp client and Retrofit. My question is how I would update the certificate pinner of the http client after retrofit has been initialized (like, when a new public key has been received)?
Do I update the CertificatePinner in the http client and then create a new instance of retrofit? Or is there an easier way?
Any suggestions appreciated.
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.certificatePinner(NetworkUtils.getCertificatePinner()) ;
OKHTTPClient client = clientBuilder.build();
Retrofit myRetrofit = new Retrofit.Builder()
.baseUrl(url)
.client(client)
.build();
// Now I need to update the certificate pinner, like this?
client.certificatePinner(NetworkUtils.getCertificatePinner());
myRetrofit = new Retrofit.Builder()
.baseUrl(url)
.client(client)
.build();
Did you try using an interceptor. Something on the lines of inner class ExpiredSessionInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val response = chain.proceed(request)
if (response.code() == 202) {
val newRequest = request.newBuilder().build()
return chain.proceed(newRequest)
} else {
return response;
}
}
}

Categories

Resources