2017-03-09 66 views
0

我試圖運行一個jar文件後,我建立在的IntelliJ gradle這個,但我發現了以下錯誤:無法運行罐子搖籃的HttpClient Dependecy

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) { 

     } 
    } 
} 

回答

3

你只是建立你的項目,通過調用:gradle這個版本(無需添加任何額外的插件,Java的除外)?如果是這樣,你的jar中沒有httpclient類。您需要使用FatJarCopy dependencies來構建您的項目。

1

您還可以擴展jar任務來收集依賴關係並將其打包,但請注意,這不是首選解決方案。我只將它用於一些小應用程序或測試。強烈建議使用插件。

jar { 
archiveName = 'Name.jar' 

manifest { 
    attributes 'Main-Class': 'your main', 
      'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' '), 
      'Implementation-Version': project.version 
} 

from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) 
}