Vivek Singh
Vivek Singh

Reputation: 1221

java.lang.NoSuchMethodError in OkHttpClient.Builder() after updating from retrofit 2.6.2 to retrofit 2.9.0

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.

Upvotes: 1

Views: 1894

Answers (3)

Birudeo Garande
Birudeo Garande

Reputation: 21

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

Upvotes: 0

Lu Alex
Lu Alex

Reputation: 66

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
}

Upvotes: 5

Ravi Kumar
Ravi Kumar

Reputation: 4528

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

Upvotes: 1

Related Questions