初始化OkHttpClient时出现java.lang.NoClassDefFoundError问题求助
问题描述
我在使用IntelliJ IDEA Ultimate开发时,尝试编写代码发起简单HTTP请求并解析响应JSON,但运行时出现错误:java.lang.NoClassDefFoundError: okhttp3/OkHttpClient。相关代码信息如下:
相关导入
import java.io.IOException; import com.google.gson.Gson; import com.google.gson.JsonObject; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
代码片段
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(String.format("http://localhost/products/%s/check?v=%s", PRODUCT_HASH, VERSION)) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); assert response.body() != null; String responseData = response.body().string(); Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(responseData, JsonObject.class); getLogger().info(jsonObject.toString()); } catch (IOException e) { getLogger().severe("Failed to check version:" + e.toString()); }
Maven依赖
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.12.0</version> </dependency>
解决建议
java.lang.NoClassDefFoundError本质是运行时类路径里找不到OkHttp的类文件,按以下步骤排查:
- 同步Maven依赖:点击IntelliJ右侧Maven面板的「Reload All Maven Projects」,确保okhttp的jar包下载到本地仓库。如果本地仓库对应目录(
~/.m2/repository/com/squareup/okhttp3/okhttp/4.12.0)没有jar包,删除该目录后重新同步。 - 检查运行配置:打开「Run/Debug Configurations」,确认当前运行配置的「Module classpath」中包含okhttp的依赖jar包。如果之前给依赖加过
provided或test这类限制运行时的scope,直接删除<scope>标签(默认compile范围会自动包含在运行时)。 - 清理重建项目:执行
mvn clean install命令清理旧编译产物并重新构建,或者在IntelliJ中点击「Build」→「Rebuild Project」。 - 补充Gson依赖:代码中用到了Gson但未提供对应依赖,建议在pom.xml中添加:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency>
内容的提问来源于stack exchange,提问作者IkonoDim
相关产品推荐
相关产品推荐

