英文:
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<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);
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("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;
}
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("com.squareup.okhttp3:okhttp:4.0.0")
api "com.squareup.retrofit2:converter-gson:2.8.1"
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 "(*)"|grep -C 10 "okhttp"
并发现okhttp的jar实际版本是3.8.1:
$ gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v "(*)"|grep -C 10 "okhttp"
\--- 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 -> 2.1
| +--- com.squareup.okhttp3:okhttp:4.0.0 -> 3.8.1
| | +--- com.squareup.okio:okio:2.2.2
| | | \--- org.jetbrains.kotlin:kotlin-stdlib:1.2.60 -> 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 -> 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:
'dependencies.dependency.systemPath' 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
'dependencies.dependency.systemPath' 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 ->
if (details.requested.group == 'com.squareup.okhttp3') {
details.useVersion "4.0.0"
}
}
}
问题已解决,希望对您有帮助!完整的配置如下:
buildscript {
apply from: "${rootProject.projectDir}/common.gradle"
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "io.spring.gradle:dependency-management-plugin:1.0.11.RELEASE"
classpath "gradle.plugin.com.arenagod.gradle:mybatis-generator-plugin:1.4"
}
}
plugins {
id 'java'
id 'idea'
id 'java-library'
id 'application'
id 'maven-publish'
id "org.springframework.boot" version "2.6.7"
id "io.freefair.lombok" version "6.4.3"
id 'com.github.ayltai.spring-graalvm-native-plugin' version '1.4.10'
id "org.springdoc.openapi-gradle-plugin" version "1.3.4"
}
apply from: "${rootProject.projectDir}/common.gradle"
subprojects {
apply plugin: 'io.freefair.lombok'
apply plugin: 'java'
apply plugin: 'maven-publish'
apply plugin: 'java-library'
apply plugin: "idea"
apply plugin: "io.spring.dependency-management"
apply plugin: 'org.springframework.boot'
apply plugin: 'org.springdoc.openapi-gradle-plugin'
configurations.all {
exclude group: "ch.qos.logback", module: "logback-classic"
exclude group: "ch.qos.logback", module: "logback-core"
exclude group: "org.apache.logging.log4j", module: "log4j-to-slf4j"
/**
* why exclude the gson?
* https://github.com/swagger-api/swagger-core/issues/1826
*/
// exclude group: "com.google.code.gson", module: "gson"
// check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
// check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'com.github.jsqlparser') {
details.useVersion "2.1"
}
//if (details.requested.group == 'redis.clients' && details.requested.name == 'jedis' ) {
// details.useVersion("4.0.0")
//}
if (details.requested.group == 'org.springframework.data'
<details>
<summary>英文:</summary>
I check the reference using gradle command like this:
gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v "(*)"|grep -C 10 "okhttp"
and find the okhttp jar actual version is 3.8.1:
$ gradle :soa-illidan:soa-illidan-service:dependencies --configuration runtimeClasspath|grep -v "(*)"|grep -C 10 "okhttp"
\--- 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 -> 2.1
| +--- com.squareup.okhttp3:okhttp:4.0.0 -> 3.8.1
| | +--- com.squareup.okio:okio:2.2.2
| | | \--- org.jetbrains.kotlin:kotlin-stdlib:1.2.60 -> 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 -> 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:
'dependencies.dependency.systemPath' 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
'dependencies.dependency.systemPath' 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 ->
if (details.requested.group == 'com.squareup.okhttp3') {
details.useVersion "4.0.0"
}
}
}
problem solved. hope helps for you! The full config look like this:
buildscript {
apply from: "${rootProject.projectDir}/common.gradle"
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "io.spring.gradle:dependency-management-plugin:1.0.11.RELEASE"
classpath "gradle.plugin.com.arenagod.gradle:mybatis-generator-plugin:1.4"
}
}
plugins {
id 'java'
id 'idea'
id 'java-library'
id 'application'
id 'maven-publish'
id "org.springframework.boot" version "2.6.7"
id "io.freefair.lombok" version "6.4.3"
id 'com.github.ayltai.spring-graalvm-native-plugin' version '1.4.10'
id "org.springdoc.openapi-gradle-plugin" version "1.3.4"
}
apply from: "${rootProject.projectDir}/common.gradle"
subprojects {
apply plugin: 'io.freefair.lombok'
apply plugin: 'java'
apply plugin: 'maven-publish'
apply plugin: 'java-library'
apply plugin: "idea"
apply plugin: "io.spring.dependency-management"
apply plugin: 'org.springframework.boot'
apply plugin: 'org.springdoc.openapi-gradle-plugin'
configurations.all {
exclude group: "ch.qos.logback", module: "logback-classic"
exclude group: "ch.qos.logback", module: "logback-core"
exclude group: "org.apache.logging.log4j", module: "log4j-to-slf4j"
/**
* why exclude the gson?
* https://github.com/swagger-api/swagger-core/issues/1826
*/
// exclude group: "com.google.code.gson", module: "gson"
// check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
// check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'com.github.jsqlparser') {
details.useVersion "2.1"
}
//if (details.requested.group == 'redis.clients' && details.requested.name == 'jedis' ) {
// details.useVersion("4.0.0")
//}
if (details.requested.group == 'org.springframework.data' && details.requested.name == 'spring-data-redis' ) {
details.useVersion("2.7.1")
}
//exclude group: "org.springframework.data", module: "spring-data-redis"
if (details.requested.group == 'org.postgresql' && details.requested.name == 'postgresql' ) {
details.useVersion("42.2.23")
}
if (details.requested.group == 'org.apache.logging.log4j' && details.requested.name == 'log4j-api' ) {
details.useVersion("2.17.0")
}
}
}
}
repositories {
if (project.hasProperty("buildEnv") && project.getProperties().get("buildEnv") == "github") {
mavenCentral()
} else {
mavenCentral()
}
}
dependencies {
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"
testImplementation "org.projectlombok:lombok:${lombokVersion}"
api "$rootProject.ext.dependencies.log4j"
api "$rootProject.ext.dependencies.slfj2Log4j"
api "$rootProject.ext.dependencies.collections4"
api "org.apache.commons:commons-lang3:${commonColleciton3Version}"
implementation "$rootProject.ext.dependencies.mybatisGeneratorCore"
implementation "$rootProject.ext.dependencies.itfswMybatisGeneratorPlugin"
testImplementation group: 'org.testng', name: 'testng', version: '7.4.0'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:$rootProject.ext.version.springCloudVersion"
}
}
}
allprojects {
sourceCompatibility = 11
targetCompatibility = 11
def defaultEncoding = 'UTF-8'
compileJava {
options.encoding = defaultEncoding
}
compileTestJava {
options.encoding = defaultEncoding
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
/**
* 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 = 'https://maven.aliyun.com/nexus/content/groups/public'
all { ArtifactRepository repo ->
if(repo instanceof MavenArtifactRepository){
def url = repo.url.toString()
if (url.startsWith('https://repo1.maven.org/maven2')) {
project.logger.lifecycle "Repository ${repo.url} replaced by $PROXY_REPOSITORY_URL."
remove repo
}
}
}
maven {
url PROXY_REPOSITORY_URL
}
/****** Release Repo ********/
maven {
credentials {
username System.getenv("ALIYUN_REPO_USERNAME")
password System.getenv("ALIYUN_REPO_PASSWORD")
}
url 'https://packages.aliyun.com/maven/repository/2236707-release-REsSq7/'
}
/****** Snapshot Repo ********/
maven {
credentials {
username System.getenv("ALIYUN_DOCKER_REPO_USER_NAME")
password System.getenv("ALIYUN_DOCKER_REPO_USER_PASSWORD")
}
url 'https://packages.aliyun.com/maven/repository/2236707-snapshot-lUlWG7/'
}
}
}
this is the `build.gradle` file location:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/VZ8MV.png
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论