I am trying to add multiple custom headers to every Request payload from my app so that a server could recognize request and ignore some of them that do not supply valid headers.
I tried to use https://square.github.io/okhttp/ to intercept my request with corresponding custom headers.
Dendencies:
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.google.code.gson:gson:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
Code for adding custom client:
OkHttpClient HttpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("header_name1","value1").build();
.addHeader("header_name2","value2").build();
return chain.proceed(request);
}
}).build();
Then, I add Custom interceptor to retrofit like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.BASE_URL)
.client(defaultHttpClient)
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
When I try to log Request, I find that headers are not added to payload, to prove this I have tested my API in postman passing headers and it is working as expected.I guess I am doing it wrong but I have tried all accepted solutions with no success. Any help to fix this would be highly appreciated.