Home > Mobile >  Headers missing from okhttpclient using custom interceptor (but work if I add statically/dynamically
Headers missing from okhttpclient using custom interceptor (but work if I add statically/dynamically

Time:01-26

I am having a bit of an issue with logging my headers.

Here is my class that implements interceptor:

public class AuthInterceptor implements Interceptor {
    private SessionManagement sessionManagement;

    public AuthInterceptor(Context ctx) {
        this.sessionManagement = new SessionManagement(ctx);
    }

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        // if token saved, add to request
        String token = sessionManagement.getSessionToken();

        if (token != null) {
            requestBuilder.addHeader("Authorization", "Bearer "   token);
        }

        return chain.proceed(requestBuilder.build());
    }

}

And here is my ApiClient class:

public class ApiClient {
    public static final String BASE_URL = "some/url";

    public static Retrofit retrofit = null;

    public static Retrofit getApiClient(Context context) {
        if (retrofit == null) {
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();

            AuthInterceptor authInterceptor = new AuthInterceptor(context);

            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(authInterceptor)
                    .addInterceptor(logging)
                    .cookieJar(cookieJar)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(okHttpClient)
                    .build();
        }

        return retrofit;
    }

}

I feel these have been implemented correctly, but I am still unable to see the headers in my logs:

2023-01-26 13:35:53.361  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  --> POST http://.../loginuser.php
2023-01-26 13:35:53.361  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Content-Type: application/json; charset=UTF-8
2023-01-26 13:35:53.361  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Content-Length: 41
2023-01-26 13:35:53.361  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  {"email":"[email protected]","password":"test1234"}
2023-01-26 13:35:53.361  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  --> END POST (41-byte body)
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  <-- 200 OK http://.../loginuser.php (96ms)
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Date: Thu, 26 Jan 2023 12:35:54 GMT
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Server: Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/8.1.10
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  X-Powered-By: PHP/8.1.10
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Expires: Thu, 19 Nov 1981 08:52:00 GMT
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Cache-Control: no-store, no-cache, must-revalidate
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Pragma: no-cache
2023-01-26 13:35:53.458  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Set-Cookie: PHPSESSID=l08iqa7cs8tvt1bfnijkl1r7d8; path=/
2023-01-26 13:35:53.459  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Content-Length: 194
2023-01-26 13:35:53.459  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Keep-Alive: timeout=5, max=100
2023-01-26 13:35:53.459  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Connection: Keep-Alive
2023-01-26 13:35:53.459  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  Content-Type: text/html; charset=UTF-8
2023-01-26 13:35:53.459  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  {"status_code":200,"auth_token":"TEMPTOKEN","user":{"id":"30","full_name":null,"username":"t","password_hash":"$2y","email":"[email protected]"}}
2023-01-26 13:35:53.459  7841-7924  okhttp.OkHttpClient     com.example.releasesapp              I  <-- END HTTP (194-byte body)

Additionally, if I completely comment out my OkHttpClient (as well as the .client(okHttpClient) line), my log still shows okhttpclient. Is this normal?

Appreciate any help I can get with this.

CodePudding user response:

try this I hope helpful you

 private final OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(1, TimeUnit.MINUTES)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS).addInterceptor(chain -> {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                 .addHeader("Authorization",sessionManagement.getSessionToken() != null ? "Bearer "   sessionManagement.getSessionToken(): "")
                    .build();
            return chain.proceed(request);
        })
        .addInterceptor(logging)
        .build();

CodePudding user response:

Interceptor that you set works in sequence that you set

It means if you set authInterceptor before logging then first authInterceptor executed and then logging will start to print so here you just need to change sequence

From

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(authInterceptor)
                    .addInterceptor(logging)
                    .cookieJar(cookieJar)
                    .build();

To

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .addInterceptor(authInterceptor)
                    .cookieJar(cookieJar)
                    .build();
  • Related