1

Earlier I was using retrofit version 2.6.2 in my project to call an api service and everything was working fine. I am creating a custom Interceptor to add the api key to the header of every request.

NetworkInterceptor.kt

class NetworkInterceptor() : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
            request = request.newBuilder()
                .addHeader("Authorization", "Client-ID ${NetworkConfig.CLIENT_ID}")
                .build()

        return chain.proceed(request)
    }
}

I updated the retrofit library to version 2.9.0 and after updating to retrofit version 2.9.0 I am getting java.lang.NoSuchMethodError in the line OkHttpClient.Builder() while adding the Interceptor to the Retrofit.Builder().

Api.kt

interface Api {

    @GET("photos")
    suspend fun getPhotos(
        @Query("page") pageNumber: Int,
        @Query("per_page") pageSize: Int,
        @Query("order_by") orderBy: String
    ) : Response<List<Photo>>

    @GET("photos/random")
    suspend fun getRandomPhoto() : Response<Photo>

    companion object{
        operator fun invoke(
            networkInterceptor: NetworkInterceptor
        ) : Api{

            val client = OkHttpClient.Builder()    //java.lang.NoSuchMethodError
                .addInterceptor(networkInterceptor)
                .build()

            return Retrofit.Builder()
                .baseUrl(NetworkConfig.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(Api::class.java)
        }
    }
}

Now I don't know how to solve this error. Any help will be appreciated.

2
  • What is your OkHttp version? Commented Jun 6, 2020 at 8:25
  • @SaurabhThorat I am not using specific dependency for OkHttp, I am using the default version that comes with retrofit. Commented Jun 6, 2020 at 8:34

3 Answers 3

5

Add the compile options inside android block of your app level build.gradle file:

android {
...

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try to rebuild your project. Make sure your project is using the latest OkHttp library 3.14.9.

3 Comments

The latest version of OkHttp is 4.7.2
@SaurabhThorat Rebuilding the project doesn't help either.
@SaurabhThorat 3.14.* is Java-based, 4.x is Kotlin-based
0

I was facing same issue, resolved after updating OkHttp library 3.14.9 from 3.10.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.