我已经创建了如下所示的build.gradle文件:
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.12.1'
}
然后,我有一个简单的helloWorld类,该类使用okhttp网站上的示例代码:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class helloWorld{
public static void main(String[] args){
System.out.println("Hello World!");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("www.google.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("SUCCESSS---->"+response.body().string());
} catch (IOException e){
System.out.println("......error thrown");
}
}
}
当我尝试运行编译的类文件时,出现以下错误:
Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/OkHttpClient at helloWorld.main(helloWorld.java:6)
Caused by: java.lang.ClassNotFoundException: okhttp3.OkHttpClient at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.
ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more
如果我删除行
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("www.google.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("SUCCESSS---->"+response.body().string());
} catch (IOException e){
System.out.println("......error thrown");
}
然后该类正确运行。所以我认为可能是坛子没有正确导入?
要清楚,项目正在正确编译,仅当我尝试运行已编译的类文件时,才会出现此问题。
答案 0 :(得分:0)
默认情况下,在创建jar时,Gradle不包括依赖项。
您可以使用shadow创建具有所有依赖项https://github.com/johnrengelman/shadow的jar 像这样:
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '4.0.4' . <----- add shadow dependency
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.12.1'
}
构建时,shadow将在构建目录或类似目录中添加另一个名为{your_project} -shadow.jar的文件。执行该操作,您应该会看到它运行。