简体   繁体   中英

NoClassDefError when using classes from a .jar

I am attempting to use classes from a .jar file in a my .java file Tweetauthent. The .jar file is in another directory. I make a request to the Twitter rest api to obtain a bearertoken. Tweetauthent compiles when I run

     -javac -cp /path/to/jar Tweetauthent.java

This is the code

import java.io.BufferedReader;
import java.lang.StringBuilder;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;

public class Tweetauthent{
 static String consumerkey = "astring";
 static String consumersecret = "astring";
 static String endurl = "https://api.twitter.com/oauth2/token";

public static void main(String []args){

    Tweetauthent t = new Tweetauthent();
    try{
        System.out.println(t.requestBearerToken(endurl));
    }catch(IOException e){
        System.out.println(e);
    }   
}
public static String encodeKeys(String consumerKey,String consumerSecret){
    try{
        String encodedConsumerKey = URLEncoder.encode(consumerKey,"UTF-8");
        String encodedConsumerSecret = URLEncoder.encode(consumerSecret,"UTF-8");

        String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
        byte[] encodedBytes = Base64.getEncoder().encode(fullKey.getBytes());
        return new String(encodedBytes);
    }catch(UnsupportedEncodingException e){
        return new String();
    }

}
public static String requestBearerToken(String endPointURL) throws IOException {
    HttpsURLConnection connection = null;
    String encodedCredentials = encodeKeys("<consumerkey>","<consumersecret>");
    try{
        URL url = new URL(endPointURL);
        connection = (HttpsURLConnection)url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Host","api.twitter.com");
        connection.setRequestProperty("User-Agent","TweetPersonalityAnalyzer");
        connection.setRequestProperty("Authorization","Basic " + encodedCredentials);
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        connection.setRequestProperty("Content-Length","29");

        writeRequest(connection, "grant_type=client_credentials");

        JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));

        if(obj != null){
            String tokenType = (String)obj.get("token_type");
            String token = (String)obj.get("access_token");

            return ((tokenType.equals("bearer")) && (token != null)) ? token : ""; 
        }
        return new String();

    }catch(MalformedURLException e){
        throw new IOException("Invalid endpoint URL specified.", e);
    }
    finally{
        if( connection != null){
            connection.disconnect();
        }
    }

}
public static boolean writeRequest(HttpsURLConnection connection, String textBody){
    try{
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        wr.write(textBody);
        wr.flush();
        wr.close();

        return true;
    }
    catch(IOException e){
        return false;
    }
}
public static String readResponse(HttpsURLConnection connection){
    try {
        StringBuilder str = new StringBuilder();

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = "";
        while((line = br.readLine()) != null){
            str.append(line + System.getProperty("line.separator"));
        }
    return str.toString();
}catch(IOException e){
    return new String();
}

}

The error I get when I run

   java Tweetauthent

is

    java.lang.NoClassDefFoundError: org/json/simple/JSONValue
          at Tweetauthent.requestBearerToken(Tweetauthent.java:61)
          at Tweetauthent.main(Tweetauthent.java:27)
    Caused by: java.lang.ClassNotFoundException: 
    org.json.simple.JSONValue
         at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
     ... 2 more

From what I understand the NoClassDefFoundError is thrown when the JVM cant find neccesary class files that the .java file used to compile. What would be causing this? Is there a way to add the path of the jar too -java? Oh and with expected consumerkey and secret strings.

UPDATE: when I add the classpath to java

    java /path/to/jar Tweethauthent

I get Error: could not find or load main class Tweetauthent

Any help would be greatly appreciated thank you!

You need to reference the runtime dependencies in -classpath or -cp option of the java command:

java -classpath /path/to/jar Tweetauthent

If you want to run with arguments add them as parameter after the Java file:

java -classpath /path/to/jar Tweetauthent <consumerkey> <consumersecret>

You have a run time class path issue.

I don't see how you've set the runtime classpath. The fact that you compiled is necessary, but insufficient.

Either you don't have the runtime classpath set properly or the JAR is not part of your package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM