我在IntelliJ中使用gradle构建后尝试运行jar文件,但我收到以下错误:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpUriRequest
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.apache.http.client.methods.HttpUriRequest
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
我的build.gradle看起来像这样:
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5.3'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
我已经在IntelliJ中的模块settigns中检查了httpcomponents和commons-codec的依赖关系。
源代码:
package com.jshah;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static org.apache.http.HttpHeaders.USER_AGENT;
public class Runner {
public static void main(String[] args) {
final String url = "http://reddit.com/api/trending_subreddits";
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(
response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
catch (Exception e) {
}
}
}
答案 0 :(得分:3)
你是通过调用gradle build来构建你的项目(不添加任何额外的插件,除了java)?如果是这样,你的jar中就没有httpclient类。您需要使用FatJar或Copy dependencies来构建项目。
答案 1 :(得分:1)
您还可以扩展jar任务以收集依赖项并将其打包,但请注意,这不是首选解决方案。我只将它用于一些小应用程序或测试。强烈建议使用插件。
windows