NoSuchMethodError: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl when using retrofit 2

huangapple go评论83阅读模式
英文:

NoSuchMethodError: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl when using retrofit 2

问题

以下是您提供的代码的翻译部分:

我正在使用 Retrofit 2 发送 HTTP 请求代码如下

ReconcileService service = RetrofitUtil.InitRetrofitOkhttp().create(ReconcileService.class);
Call<ResponseBody> call = service.page(request);
ResponseBody body = call.execute().body();
String str = new String(body.bytes(), "UTF-8");
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(str, Response.class);

这是 Retrofit 的初始化代码

public static Retrofit InitRetrofitOkhttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        Config config = ConfigService.getAppConfig();
        String baseUrl = config.getProperty("robot.retrofit.base-url", "127.0.0.1");
        OkHttpClient client = builder.build();
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.client(client);
        retrofitBuilder.baseUrl(baseUrl);
        Retrofit sRetrofit = retrofitBuilder.build();
        return sRetrofit;
    }

但是在运行此代码时它给了我提示

	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212]
Caused by: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl;
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) [spring-webmvc-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
	... 55 common frames omitted
Caused by: java.lang.NoSuchMethodError: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl;
	at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:492) ~[retrofit-2.8.1.jar!/:na]
	at com.sportswin.soa.misc.biz.common.RetrofitUtil.InitRetrofitOkhttp(RetrofitUtil.java:42) ~[soa-misc-biz-1.0.0-SNAPSHOT.jar!/:na]
	at com.sportswin.soa.illidan.controller.impl.tenant.ReconcilationController.getRes(ReconcilationController.java:38) ~[classes!/:na]
	at com.sportswin.soa.illidan.controller.impl.tenant.ReconcilationController.tenantPage(ReconcilationController.java:31) ~[classes!/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_212]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_212]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_212]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) [spring-web-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]

我尝试从互联网上找答案但所有的建议都是升级 okhttp 版本但是现在我的 okhttp 版本已经是 4.0这是我的 Gradle 配置

api("com.squareup.okhttp3:okhttp:4.0.0")
api "com.squareup.retrofit2:converter-gson:2.8.1"

所以问题在哪里我应该怎么做才能解决它

请注意,我已经根据您的要求只返回了翻译好的部分,没有包含其他内容。如果您有任何其他问题或需要进一步的帮助,请随时提出。

英文:

I am using retrofit 2 to send a http request, code like this:

            ReconcileService service = RetrofitUtil.InitRetrofitOkhttp().create(ReconcileService.class);
Call&lt;ResponseBody&gt; call = service.page(request);
ResponseBody body = call.execute().body();
String str = new String(body.bytes(), &quot;UTF-8&quot;);
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(str, Response.class);

this is the retrofit initial code:

public static Retrofit InitRetrofitOkhttp() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
builder.retryOnConnectionFailure(true);
Config config = ConfigService.getAppConfig();
String baseUrl = config.getProperty(&quot;robot.retrofit.base-url&quot;, &quot;127.0.0.1&quot;);
OkHttpClient client = builder.build();
Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
retrofitBuilder.client(client);
retrofitBuilder.baseUrl(baseUrl);
Retrofit sRetrofit = retrofitBuilder.build();
return sRetrofit;
}

but when running this code, it give me tips:

	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212]
Caused by: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl;
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) [spring-webmvc-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
... 55 common frames omitted
Caused by: java.lang.NoSuchMethodError: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl;
at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:492) ~[retrofit-2.8.1.jar!/:na]
at com.sportswin.soa.misc.biz.common.RetrofitUtil.InitRetrofitOkhttp(RetrofitUtil.java:42) ~[soa-misc-biz-1.0.0-SNAPSHOT.jar!/:na]
at com.sportswin.soa.illidan.controller.impl.tenant.ReconcilationController.getRes(ReconcilationController.java:38) ~[classes!/:na]
at com.sportswin.soa.illidan.controller.impl.tenant.ReconcilationController.tenantPage(ReconcilationController.java:31) ~[classes!/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_212]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_212]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_212]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) [spring-web-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]

I try to find answer from internet but all told to upgrade the okhttp version. But now my okhttp version already 4.0, this is my gradle config:

api(&quot;com.squareup.okhttp3:okhttp:4.0.0&quot;)
api &quot;com.squareup.retrofit2:converter-gson:2.8.1&quot;

so where is the problem and what should I do to fix it?

答案1

得分: 2

我使用gradle命令检查引用,类似于这样:

gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v &quot;(*)&quot;|grep -C 10 &quot;okhttp&quot;

并发现okhttp的jar实际版本是3.8.1:

$ gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v &quot;(*)&quot;|grep -C 10 &quot;okhttp&quot;
\--- project :soa-illidan:soa-illidan-api
+--- log4j:log4j:1.2.17
+--- org.apache.commons:commons-collections4:4.4
+--- org.apache.commons:commons-lang3:3.9
+--- project :soa-misc-biz
|    +--- log4j:log4j:1.2.17
|    +--- org.apache.commons:commons-collections4:4.4
|    +--- org.apache.commons:commons-lang3:3.9
|    +--- com.github.pagehelper:pagehelper:5.1.11
|    |    \--- com.github.jsqlparser:jsqlparser:2.0 -&gt; 2.1
|    +--- com.squareup.okhttp3:okhttp:4.0.0 -&gt; 3.8.1
|    |    +--- com.squareup.okio:okio:2.2.2
|    |    |    \--- org.jetbrains.kotlin:kotlin-stdlib:1.2.60 -&gt; 1.2.71
|    |    |         +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.2.71
|    |    |         \--- org.jetbrains:annotations:13.0
|    +--- com.squareup.retrofit2:converter-gson:2.8.1
|    |    +--- com.squareup.retrofit2:retrofit:2.8.1
|    |    \--- com.google.code.gson:gson:2.8.5 -&gt; 2.8.6
|    +--- project :soa-misc
|    |    +--- log4j:log4j:1.2.17
|    |    +--- org.apache.commons:commons-collections4:4.4
Errors occurred while build effective model from /Users/dolphin/.gradle/caches/modules-2/files-2.1/com.alibaba/druid/1.1.9/e6a9ff9e84dd1c498d9e12373331fbacd92d330a/druid-1.1.9.pom:
&#39;dependencies.dependency.systemPath&#39; for com.alibaba:jconsole:jar must specify an absolute path but is ${env.JAVA_HOME}/lib/jconsole.jar in com.alibaba:druid:1.1.9
&#39;dependencies.dependency.systemPath&#39; for com.alibaba:tools:jar must specify an absolute path but is ${env.JAVA_HOME}/lib/tools.jar in com.alibaba:druid:1.1.9

所以,我在buil.gradle中添加了以下内容以强制使用okhttp的4.0.0版本:

resolutionStrategy {
eachDependency { DependencyResolveDetails details -&gt;
if (details.requested.group == &#39;com.squareup.okhttp3&#39;) {
details.useVersion &quot;4.0.0&quot;
}
}
}

问题已解决,希望对您有帮助!完整的配置如下:

buildscript {
    apply from: &quot;${rootProject.projectDir}/common.gradle&quot;

    repositories {
        maven {
            url &quot;https://plugins.gradle.org/m2/&quot;
        }
    }
    dependencies {
        classpath &quot;io.spring.gradle:dependency-management-plugin:1.0.11.RELEASE&quot;
        classpath &quot;gradle.plugin.com.arenagod.gradle:mybatis-generator-plugin:1.4&quot;
    }
}

plugins {
    id &#39;java&#39;
    id &#39;idea&#39;
    id &#39;java-library&#39;
    id &#39;application&#39;
    id &#39;maven-publish&#39;
    id &quot;org.springframework.boot&quot; version &quot;2.6.7&quot;
    id &quot;io.freefair.lombok&quot; version &quot;6.4.3&quot;
    id &#39;com.github.ayltai.spring-graalvm-native-plugin&#39; version &#39;1.4.10&#39;
    id &quot;org.springdoc.openapi-gradle-plugin&quot; version &quot;1.3.4&quot;

}

apply from: &quot;${rootProject.projectDir}/common.gradle&quot;

subprojects {
    apply plugin: &#39;io.freefair.lombok&#39;
    apply plugin: &#39;java&#39;
    apply plugin: &#39;maven-publish&#39;
    apply plugin: &#39;java-library&#39;
    apply plugin: &quot;idea&quot;
    apply plugin: &quot;io.spring.dependency-management&quot;
    apply plugin: &#39;org.springframework.boot&#39;
    apply plugin: &#39;org.springdoc.openapi-gradle-plugin&#39;


    configurations.all {
        exclude group: &quot;ch.qos.logback&quot;, module: &quot;logback-classic&quot;
        exclude group: &quot;ch.qos.logback&quot;, module: &quot;logback-core&quot;
        exclude group: &quot;org.apache.logging.log4j&quot;, module: &quot;log4j-to-slf4j&quot;
        /**
         * why exclude the gson?
         * https://github.com/swagger-api/swagger-core/issues/1826
         */
        // exclude group: &quot;com.google.code.gson&quot;, module: &quot;gson&quot;

        // check for updates every build
        resolutionStrategy.cacheChangingModulesFor 0, &#39;seconds&#39;

        // check for updates every build
        resolutionStrategy.cacheChangingModulesFor 0, &#39;seconds&#39;

        resolutionStrategy {
            eachDependency { DependencyResolveDetails details -&gt;
                if (details.requested.group == &#39;com.github.jsqlparser&#39;) {
                    details.useVersion &quot;2.1&quot;
                }
                //if (details.requested.group == &#39;redis.clients&#39; &amp;&amp; details.requested.name == &#39;jedis&#39; ) {
                //    details.useVersion(&quot;4.0.0&quot;)
                //}
                if (details.requested.group == &#39;org.springframework.data&#39;

<details>
<summary>英文:</summary>

I check the reference using gradle command like this:


    gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v &quot;(*)&quot;|grep -C 10 &quot;okhttp&quot;



and find the okhttp jar actual version is 3.8.1:


    $ gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v &quot;(*)&quot;|grep -C 10 &quot;okhttp&quot;
    \--- project :soa-illidan:soa-illidan-api
         +--- log4j:log4j:1.2.17
         +--- org.apache.commons:commons-collections4:4.4
         +--- org.apache.commons:commons-lang3:3.9
         +--- project :soa-misc-biz
         |    +--- log4j:log4j:1.2.17
         |    +--- org.apache.commons:commons-collections4:4.4
         |    +--- org.apache.commons:commons-lang3:3.9
         |    +--- com.github.pagehelper:pagehelper:5.1.11
         |    |    \--- com.github.jsqlparser:jsqlparser:2.0 -&gt; 2.1
         |    +--- com.squareup.okhttp3:okhttp:4.0.0 -&gt; 3.8.1
         |    |    +--- com.squareup.okio:okio:2.2.2
         |    |    |    \--- org.jetbrains.kotlin:kotlin-stdlib:1.2.60 -&gt; 1.2.71
         |    |    |         +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.2.71
         |    |    |         \--- org.jetbrains:annotations:13.0
         |    +--- com.squareup.retrofit2:converter-gson:2.8.1
         |    |    +--- com.squareup.retrofit2:retrofit:2.8.1
         |    |    \--- com.google.code.gson:gson:2.8.5 -&gt; 2.8.6
         |    +--- project :soa-misc
         |    |    +--- log4j:log4j:1.2.17
         |    |    +--- org.apache.commons:commons-collections4:4.4
    Errors occurred while build effective model from /Users/dolphin/.gradle/caches/modules-2/files-2.1/com.alibaba/druid/1.1.9/e6a9ff9e84dd1c498d9e12373331fbacd92d330a/druid-1.1.9.pom:
        &#39;dependencies.dependency.systemPath&#39; for com.alibaba:jconsole:jar must specify an absolute path but is ${env.JAVA_HOME}/lib/jconsole.jar in com.alibaba:druid:1.1.9
        &#39;dependencies.dependency.systemPath&#39; for com.alibaba:tools:jar must specify an absolute path but is ${env.JAVA_HOME}/lib/tools.jar in com.alibaba:druid:1.1.9



so I add this in the `buil.gradle` to force using 4.0.0 version of okhttp:


     resolutionStrategy {
                eachDependency { DependencyResolveDetails details -&gt;
                   
                    if (details.requested.group == &#39;com.squareup.okhttp3&#39;) {
                        details.useVersion &quot;4.0.0&quot;
                    }
                }
            }




problem solved. hope helps for you! The full config look like this:




    buildscript {
        apply from: &quot;${rootProject.projectDir}/common.gradle&quot;
    
        repositories {
            maven {
                url &quot;https://plugins.gradle.org/m2/&quot;
            }
        }
        dependencies {
            classpath &quot;io.spring.gradle:dependency-management-plugin:1.0.11.RELEASE&quot;
            classpath &quot;gradle.plugin.com.arenagod.gradle:mybatis-generator-plugin:1.4&quot;
        }
    }
    
    plugins {
        id &#39;java&#39;
        id &#39;idea&#39;
        id &#39;java-library&#39;
        id &#39;application&#39;
        id &#39;maven-publish&#39;
        id &quot;org.springframework.boot&quot; version &quot;2.6.7&quot;
        id &quot;io.freefair.lombok&quot; version &quot;6.4.3&quot;
        id &#39;com.github.ayltai.spring-graalvm-native-plugin&#39; version &#39;1.4.10&#39;
        id &quot;org.springdoc.openapi-gradle-plugin&quot; version &quot;1.3.4&quot;
    
    }
    
    apply from: &quot;${rootProject.projectDir}/common.gradle&quot;
    
    subprojects {
        apply plugin: &#39;io.freefair.lombok&#39;
        apply plugin: &#39;java&#39;
        apply plugin: &#39;maven-publish&#39;
        apply plugin: &#39;java-library&#39;
        apply plugin: &quot;idea&quot;
        apply plugin: &quot;io.spring.dependency-management&quot;
        apply plugin: &#39;org.springframework.boot&#39;
        apply plugin: &#39;org.springdoc.openapi-gradle-plugin&#39;
    
    
        configurations.all {
            exclude group: &quot;ch.qos.logback&quot;, module: &quot;logback-classic&quot;
            exclude group: &quot;ch.qos.logback&quot;, module: &quot;logback-core&quot;
            exclude group: &quot;org.apache.logging.log4j&quot;, module: &quot;log4j-to-slf4j&quot;
            /**
             * why exclude the gson?
             * https://github.com/swagger-api/swagger-core/issues/1826
             */
            // exclude group: &quot;com.google.code.gson&quot;, module: &quot;gson&quot;
    
            // check for updates every build
            resolutionStrategy.cacheChangingModulesFor 0, &#39;seconds&#39;
    
            // check for updates every build
            resolutionStrategy.cacheChangingModulesFor 0, &#39;seconds&#39;
    
            resolutionStrategy {
                eachDependency { DependencyResolveDetails details -&gt;
                    if (details.requested.group == &#39;com.github.jsqlparser&#39;) {
                        details.useVersion &quot;2.1&quot;
                    }
                    //if (details.requested.group == &#39;redis.clients&#39; &amp;&amp; details.requested.name == &#39;jedis&#39; ) {
                    //    details.useVersion(&quot;4.0.0&quot;)
                    //}
                    if (details.requested.group == &#39;org.springframework.data&#39; &amp;&amp; details.requested.name == &#39;spring-data-redis&#39; ) {
                        details.useVersion(&quot;2.7.1&quot;)
                    }
                    //exclude group: &quot;org.springframework.data&quot;, module: &quot;spring-data-redis&quot;
                    if (details.requested.group == &#39;org.postgresql&#39; &amp;&amp; details.requested.name == &#39;postgresql&#39; ) {
                        details.useVersion(&quot;42.2.23&quot;)
                    }
                    if (details.requested.group == &#39;org.apache.logging.log4j&#39; &amp;&amp; details.requested.name == &#39;log4j-api&#39; ) {
                        details.useVersion(&quot;2.17.0&quot;)
                    }
                }
            }
        }
    
        repositories {
            if (project.hasProperty(&quot;buildEnv&quot;) &amp;&amp; project.getProperties().get(&quot;buildEnv&quot;) == &quot;github&quot;) {
                mavenCentral()
            } else {
                mavenCentral()
            }
        }
    
        dependencies {
            compileOnly &quot;org.projectlombok:lombok:${lombokVersion}&quot;
            annotationProcessor &quot;org.projectlombok:lombok:${lombokVersion}&quot;
            testAnnotationProcessor &quot;org.projectlombok:lombok:${lombokVersion}&quot;
            testImplementation &quot;org.projectlombok:lombok:${lombokVersion}&quot;
            api &quot;$rootProject.ext.dependencies.log4j&quot;
            api &quot;$rootProject.ext.dependencies.slfj2Log4j&quot;
            api &quot;$rootProject.ext.dependencies.collections4&quot;
            api &quot;org.apache.commons:commons-lang3:${commonColleciton3Version}&quot;
            implementation &quot;$rootProject.ext.dependencies.mybatisGeneratorCore&quot;
            implementation &quot;$rootProject.ext.dependencies.itfswMybatisGeneratorPlugin&quot;
            testImplementation group: &#39;org.testng&#39;, name: &#39;testng&#39;, version: &#39;7.4.0&#39;
        }
    
        dependencyManagement {
            imports {
                mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:$rootProject.ext.version.springCloudVersion&quot;
            }
        }
    }
    
    allprojects {
        sourceCompatibility = 11
        targetCompatibility = 11
        def defaultEncoding = &#39;UTF-8&#39;
        compileJava {
            options.encoding = defaultEncoding
        }
        compileTestJava {
            options.encoding = defaultEncoding
        }
        tasks.withType(JavaCompile) {
            options.encoding = &#39;UTF-8&#39;
        }
    
        /**
         * remove aliyun repo config from ~/.gradle/init.gradle into project
         * avoid to force other project in machine use aliyun
         * some international project could not fetch dependencies from aliyun
         */
        repositories {
            def PROXY_REPOSITORY_URL = &#39;https://maven.aliyun.com/nexus/content/groups/public&#39;
            all { ArtifactRepository repo -&gt;
                if(repo instanceof MavenArtifactRepository){
                    def url = repo.url.toString()
                    if (url.startsWith(&#39;https://repo1.maven.org/maven2&#39;)) {
                        project.logger.lifecycle &quot;Repository ${repo.url} replaced by $PROXY_REPOSITORY_URL.&quot;
                        remove repo
                    }
                }
            }
            maven {
                url PROXY_REPOSITORY_URL
            }
            /****** Release Repo ********/
            maven {
                credentials {
                    username System.getenv(&quot;ALIYUN_REPO_USERNAME&quot;)
                    password System.getenv(&quot;ALIYUN_REPO_PASSWORD&quot;)
                }
                url &#39;https://packages.aliyun.com/maven/repository/2236707-release-REsSq7/&#39;
            }
            /****** Snapshot Repo ********/
            maven {
                credentials {
                    username System.getenv(&quot;ALIYUN_DOCKER_REPO_USER_NAME&quot;)
                    password System.getenv(&quot;ALIYUN_DOCKER_REPO_USER_PASSWORD&quot;)
                }
                url &#39;https://packages.aliyun.com/maven/repository/2236707-snapshot-lUlWG7/&#39;
            }
        }
    }


this is the `build.gradle` file location:

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/VZ8MV.png

</details>



huangapple
  • 本文由 发表于 2020年8月8日 12:14:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63311733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定