I have this interceptor that i add to my OkHttp client:
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Here where we'll try to refresh token.
// with an retrofit call
// After we succeed we'll proceed our request
Response response = chain.proceed(request);
return response;
}
}
How can i add headers to request in my interceptor?
I tried this but i am making mistake and i lose my request when creating new request:
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request newRequest;
try {
Log.d("addHeader", "Before");
String token = TokenProvider.getInstance(mContext).getToken();
newRequest = request.newBuilder()
.addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION + token)
.addHeader(HeadersContract.HEADER_CLIENT_ID, CLIENT_ID)
.build();
} catch (Exception e) {
Log.d("addHeader", "Error");
e.printStackTrace();
return chain.proceed(request);
}
Log.d("addHeader", "after");
return chain.proceed(newRequest);
}
}
Note that, i know i can add header when creating request like this:
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
But it doesn't fit my needs. I need it in interceptor.
you can do it this way
Faced similar issue with other samples, this Kotlin class worked for me
here is a useful gist from lfmingo
If you are using Retrofit library then you can directly pass header to api request using
@Header
annotation without use of Interceptor. Here is example that shows how to add header to Retrofit api request.Hope it helps!
There is yet an another way to add interceptors in your OkHttp3 (latest version as of now) , that is you add the interceptors to your Okhttp builder
and finally build your okHttpClient from this builder
Finally, I added the headers this way: