1

There seems to be some discrepancy between using method headers and intercepting headers with OKHTTP and retrofit.

I'm looking to intercept each retrofit request going through my retrofit interface. I've written an Interceptor to go through OKHTTP like so:

OkHttpClient client = new OkHttpClient();
client.interceptors()
        .add(ThisClass::onRequestIntercept);
...
private static Response onRequestIntercept(Interceptor.Chain chain) throws IOException {
    Request original = chain.request();
    Request request = original.newBuilder()
        .header("Authorization", "auth")
        .header("Accept", "json")
        .method(original.method(), original.body())
        .build();
    return chain.proceed(request);
}

But the server throws a 401 error unless I also add the following above each and every method in the retrofit interface:

@Headers({
  "Authorization: auth",
  "Accept: json"
    })

The logs are identical for both headers with and without the second header annotation - only that the one with the second header directly above the method goes through with 200, and if only the intercepted code is used it returns a 401 error code.

What could be the discrepancy?

  • You can try to remove headers before adding the new ones as seen here http://stackoverflow.com/a/33052556/4621448 – tochkov Dec 16 '15 at 10:49
  • Doesn't seem to be the issue, the logs are identical - and show identical headers on any combination of @Headers and the interceptor. – Boris Kachscovsky Dec 16 '15 at 11:55
  • It seems there's a bug with respect to the Content-Type header (which i did not use as an example in code above). The Content-Type is being reset by retrofit to json rather than what I set in the interceptor. – Boris Kachscovsky Dec 16 '15 at 13:29
  • Your `method(original.method(), original.body())` is redundant, but I doubt that's the case. Can you please add the code where you initialize Retrofit, and the code with your service interface? – tochkov Dec 16 '15 at 14:35

0 Answers0