How can I debug my retrofit API call?

Viewed 31568

I'm using retrofit to get some data from the Flickr api. The method I'm making the call in looks like this:

public static List<String> getImageIds(int size) {
    Call<PhotosList> call = flickrService.getPhotos(apiKey, format, "1");
    Log.d("TEMP_TAG", "photo url: " + call.request().url().toString());
    photoIds = new ArrayList<String>();

    call.enqueue(new Callback<PhotosList>(){
        @Override
        public void onResponse(Call<PhotosList> call, Response<PhotosList> response) {
            Log.d("TEMP_TAG", "it's getting here");
            PhotosList photosList = response.body();
            List<Photo> photos = photosList.getPhotos().getPhoto();

            for(Photo photo : photos) {
                Log.d("TEMP_TAG", "adding photo id to list: " + photo.getId());
                photoIds.add(photo.getId());
            }
        }

        @Override
        public void onFailure(Call<PhotosList> call, Throwable t) {
            // TODO: Clean up
            Log.d("TEMP_TAG", "photoId: ");
        }
    });
    Log.d("TEMP_TAG", "it's getting here too");
    return photoIds;
}

However it is never getting into the onResponse() method. The first log statement within onResponse() never prints, neither does the log statement in onFailure(). When I try entering the URL that is returned by call.request().url().toString() in the browser it works fine, and I get the expected JSON. Why is my enqueue() method never firing?

Thanks for any help!

3 Answers

You can use the following class to log API calls

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor

object HTTPLogger {
    fun getLogger(): OkHttpClient {
        /*
         * OKHTTP interceptor to log all API calls
         */
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build()
        return client
    }
}

You can then call this class in your retrofit instance class like this

import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClientInstance {
    private var retrofit: Retrofit? = null
    val retrofitInstance: Retrofit?
        get() {
            if (retrofit == null) {
                retrofit = Retrofit.Builder()
                        .baseUrl(Constants.BASE_URL)
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(HTTPLogger.getLogger())
                        .build()
            }
            return retrofit
        }
}

The dependency required is

implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
Related