我正在调用一个单独的类,我已经在同一个包中编写了保存我的MainActivity
类。但是当我运行应用程序时它会给我java.lang.NoClassDefFoundError
。我无法理解为什么无法识别在同一个包中定义的另一个类。我已经为java.lang.NoClassDefFoundError
尝试了许多方法建议但是没有任何方法可以解决错误。
08-26 10:43:27.776: E/dalvikvm(1311): Could not find class 'com.example.hcpandroid.SSLAuthenticate$1', referenced from method com.example.hcpandroid SSLAuthenticate.authenticate
08-26 10:43:27.786: E/AndroidRuntime(1311): FATAL EXCEPTION: main
08-26 10:43:27.786: E/AndroidRuntime(1311): java.lang.NoClassDefFoundError: com.example.hcpandroid.SSLAuthenticate$1
08-26 10:43:27.786: E/AndroidRuntime(1311): at com.example.hcpandroid.SSLAuthenticate.authenticate(SSLAuthenticate.java:86)
08-26 10:43:27.786: E/AndroidRuntime(1311): at com.example.hcpandroid.LogIn.LogIn(LogIn.java:48)
08-26 10:43:27.786: E/AndroidRuntime(1311): at com.example.hcpandroid.LogIn$1.onClick(LogIn.java:29)
08-26 10:43:27.786: E/AndroidRuntime(1311): at android.view.View.performClick(View.java:4128)
08-26 10:43:27.786: E/AndroidRuntime(1311): at android.view.View$PerformClick.run(View.java:17142)
08-26 10:43:27.786: E/AndroidRuntime(1311): at android.os.Handler.handleCallback(Handler.java:615)
08-26 10:43:27.786: E/AndroidRuntime(1311): at android.os.Handler.dispatchMessage(Handler.java:92)
08-26 10:43:27.786: E/AndroidRuntime(1311): at android.os.Looper.loop(Looper.java:213)
08-26 10:43:27.786: E/AndroidRuntime(1311): at android.app.ActivityThread.main(ActivityThread.java:4787)
08-26 10:43:27.786: E/AndroidRuntime(1311): at java.lang.reflect.Method.invokeNative(Native Method)
08-26 10:43:27.786: E/AndroidRuntime(1311): at java.lang.reflect.Method.invoke(Method.java:511)
08-26 10:43:27.786: E/AndroidRuntime(1311): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
08-26 10:43:27.786: E/AndroidRuntime(1311): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
08-26 10:43:27.786: E/AndroidRuntime(1311): at dalvik.system.NativeStart.main(Native Method)
主要活动类:
package com.example.hcpandroid;
import com.example.hcpandroid.R.id;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.hcpandroid.SSLAuthenticate;
public class LogIn extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
Button btnLogIn = (Button) findViewById(id.btnLogIn);
btnLogIn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LogIn();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.log_in, menu);
return true;
}
public void LogIn(){
EditText txtUname = (EditText) findViewById(id.txtUsername);
EditText txtPword = (EditText) findViewById(id.txtPassword);
SSLAuthenticate ssl = new SSLAuthenticate(txtUname.getText().toString(), txtPword.getText().toString());
int authCode = ssl.authenticate();
Toast toast= Toast.makeText(getApplicationContext(), authCode, Toast.LENGTH_LONG);
toast.show();
}
}
SSLAuthentication类:
package com.example.hcpandroid;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONValue;
import sun.misc.BASE64Encoder;
/**
* @author sajithru
*/
public class SSLAuthenticate {
private String username;
private String password;
private DefaultHttpClient httpClient;
private String cookie;
public SSLAuthenticate(String username, String password) {
this.username = username;
this.password = password;
}
public SSLAuthenticate() {
}
public DefaultHttpClient getHttpClient() {
return httpClient;
}
public String getCookie() {
return cookie;
}
public String getUsername() {
return username;
}
public int authenticate() {
HttpResponse responce = null;
try {
//Authenticate SSL Certification
TrustStrategy easyStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// eh, why not?
return true;
}
};
SchemeRegistry schemeRegistry = new SchemeRegistry();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, null, null);
SSLSocketFactory ssf = new SSLSocketFactory((KeyStore) easyStrategy);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme httpsScheme = new Scheme("https", ssf, 443);
schemeRegistry.register(httpsScheme);
TrustManager trustMgr = new TrustManager() {
};
sslcontext.init(null, new TrustManager[]{trustMgr}, null);
HttpParams params = new BasicHttpParams();
ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schemeRegistry);
httpClient = new DefaultHttpClient(connMgr, params);
//Encode username into BASE64 encode format
BASE64Encoder base64Encoder = new BASE64Encoder();
String uname64 = base64Encoder.encode(username.getBytes());
//Encode password into MD5 Hash encode format
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(password.getBytes(), 0, password.length());
String md5Password = new BigInteger(1, messageDigest.digest()).toString(16);
//Set HTTPS request header- Authentication
cookie = "hcp-ns-auth=" + uname64 + ":" + md5Password;
System.out.println("Username: " + username + " Password: " + password);
System.out.println(cookie);
responce = adminAuth(cookie, httpClient);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyManagementException ex) {
Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyStoreException ex) {
Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex);
}
int responceCode = responce.getStatusLine().getStatusCode();
return responceCode;
}
private HttpResponse adminAuth(String cookie, HttpClient hClient) {
HttpResponse response = null;
try {
//Creating HTTP Post object
String url = "https://millennium-test.hcp.millenniumit.com/query";
//String url = "https://hitachi.hcp1.hdspoc.com/query";
HttpPost httpPost = new HttpPost(url);
httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
//Setting HTTP Post headers for Authentication, Request type, Respond type and Encode type
httpPost.addHeader("Cookie", cookie);
httpPost.addHeader("Content-Type", "application/xml");
httpPost.addHeader("Accept", "application/json");
//httpPost.addHeader("Content-Encoding", "gzip");
//httpPost.addHeader("Accept-Encoding", "gzip");
Map<String, String> obj = new LinkedHashMap<String, String>();
obj.put("query", "+(namespace:\"data-set1.Millennium-Test\")");
obj.put("contentProperties", "false");
obj.put("objectProperties", "shred,retention");
obj.put("sort", "changeTimeMilliseconds+asc");
String jsonText = "{\"object\" :" + JSONValue.toJSONString(obj) + "}";
System.out.println(jsonText);
XMLSerializer serializer = new XMLSerializer();
JSON json = JSONSerializer.toJSON(jsonText);
serializer.setRootName("queryRequest");
serializer.setTypeHintsEnabled(false);
String xml = serializer.write(json);
xml = xml.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
System.out.println(xml);
StringEntity stringEntity = new StringEntity(xml, HTTP.UTF_8);
httpPost.setEntity(stringEntity);
response = hClient.execute(httpPost);
System.out.println(response.toString());
String sJson = EntityUtils.toString(response.getEntity());
System.out.println(sJson);
HCP_Logger myLogger = new HCP_Logger();
myLogger.writeToLog(username, xml, response.toString());
} catch (IOException ex) {
Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex);
}
return response;
}
private HttpResponse tenantAuth(String cookie, HttpClient hClient) {
HttpResponse response = null;
try {
//Creating HTTP Post object
String url = "sample url";
//String url = "sample url";
HttpPost httpPost = new HttpPost(url);
httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
//Setting HTTP Post headers for Authentication, Request type, Respond type and Encode type
httpPost.addHeader("Cookie", cookie);
httpPost.addHeader("Content-Type", "application/xml");
httpPost.addHeader("Accept", "application/json");
//httpPost.addHeader("Content-Encoding", "gzip");
//httpPost.addHeader("Accept-Encoding", "gzip");
Map obj = new LinkedHashMap();
obj.put("query", "+(namespace:\"sample")");
obj.put("contentProperties", "false");
obj.put("objectProperties", "shred,retention");
obj.put("sort", "changeTimeMilliseconds+asc");
String jsonText = "{\"object\" :" + JSONValue.toJSONString(obj) + "}";
//System.out.println(jsonText);
XMLSerializer serializer = new XMLSerializer();
JSON json = JSONSerializer.toJSON(jsonText);
serializer.setRootName("queryRequest");
serializer.setTypeHintsEnabled(false);
String xml = serializer.write(json);
xml = xml.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
//System.out.println(xml);
//String xmll = "<queryRequest><object><query>namespace:\"data-set1.Millennium-Test\"</query><objectProperties>shred,retention</objectProperties><sort>changeTimeMilliseconds+asc</sort></object></queryRequest>";
//System.out.println(xmll);
StringEntity stringEntity = new StringEntity(xml, HTTP.UTF_8);
httpPost.setEntity(stringEntity);
response = hClient.execute(httpPost);
//System.out.println(response.toString());
// String sJson = EntityUtils.toString(response.getEntity());
//System.out.println(sJson);
// HCP_Logger myLogger = new HCP_Logger();
// myLogger.writeToLog(username, xml, response.toString());
} catch (IOException ex) {
Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex);
}
return response;
}
}
更新:
我想我发现了导致错误的原因。我在课堂上使用的库就是例外。我在我的班级里面使用了httpclient-4.2.5.jar,jackson-core-2.2.0.jar,json-lib-2.4-jdk15.jar,json-simple-1.1.1.jar和rt.jar。是否有任何方法可以使用这些库而不会导致异常?
答案 0 :(得分:7)
右键单击
project -> Build Path -> Configure Build Path -> Order and Export Tab.
确保选中“Android私有库”进行导出。
如果您已从libs /文件夹中添加了任何库,请将其删除,因为它们会自动添加到“Android私有库”部分中。
答案 1 :(得分:2)
右键点击项目 - &gt;属性 - &GT; Java构建路径 - &gt;订单和导出选项卡,然后选择您的私人库。
答案 2 :(得分:0)
在MainActivity类中:import com.example.hcpandroid.SSLAuthenticate; 然后,如果您已导入外部库jar文件,则将它们导入LIB文件夹。
右键单击您的项目 - &gt;属性 - &gt; Java构建路径 - &gt;订单和出口 - &gt;全选 - &gt;按OK - &gt;去清理你的项目。
希望这能解决你的问题。