why base64 class is not found when code compiles ok and classpath is set

Why code below gives error

C:temp>java Test -cp commons-codec-1.9.jar auth string: xxx Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/co dec/binary/Base64 at Test.main(Test.java:22) Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.binary.Bas e64 at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 1 more

Code

import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class Test {

    public static void main(String[] args) {

        try {
            String webPage = "xx";
            String name = "xxx";
            String password = "xx";

            String authString = name + ":" + password;
            System.out.println("auth string: " + authString);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            System.out.println("Base64 encoded auth string: " + authStringEnc);

            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }
            String result = sb.toString();

            System.out.println("*** BEGIN ***");
            System.out.println(result);
            System.out.println("*** END ***");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Try placing the cp flag in the command before the class name:

java -cp commons-codec-1.9.jar Test

This is from the java command:

Usage: java [-options] class [args...]

(to execute a class)

链接地址: http://www.djcxy.com/p/20266.html

上一篇: 在执行OWL API时出错

下一篇: 为什么base64类没有找到代码编译好,并设置类路径