Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NoSuchFieldError: Companion when using okhttp3 and selenium

I'm using Retrofit2 and Okhttp to make HTTP calls in my project, that also uses Selenium. As soon as I added the following dependency:

    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>logging-interceptor</artifactId>
        <version>4.9.0</version>
    </dependency>

I started to see the following error:

java.lang.NoSuchFieldError: Companion
at okhttp3.logging.HttpLoggingInterceptor$Logger$Companion$DefaultLogger.log(HttpLoggingInterceptor.kt:116)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.kt:168)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:204)

I have checked some related issues and everything points to a dependency problem. However, I'm using the latest versions for Okhttp and Retrofit2 (2.9.0), as well as for selenium-java:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>

What I'm trying to do is just to log a simple request using:

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

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    httpClient.addInterceptor(logging);


    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(url)
            .client(httpClient.build())
            .build();

Do you know what could be the issue?

I'm using the latest Kotlin plugin in IntelliJ

like image 543
hfc Avatar asked Jan 21 '21 13:01

hfc


1 Answers

It's most likely a dependency problem. See which JARs are imported in your IDE then debug the error. Otherwise make a simple standalone android project to run this code. You can also use the okhttp bom to upgrade cleanly to 4.9.0.

https://github.com/square/okhttp#releases

    dependencies {
       // define a BOM and its version
       implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.0"))
       
       // define any required OkHttp artifacts without version
       implementation("com.squareup.okhttp3:okhttp")
       implementation("com.squareup.okhttp3:logging-interceptor")
    }
like image 131
Yuri Schimke Avatar answered Oct 28 '22 12:10

Yuri Schimke