我用来成功连接LDAP服务器的代码如下:
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.unboundid.ldap.sdk.AddRequest;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
public class MainActivity extends Activity implements OnClickListener {
//String address="ldap://server1.mydomain.com" ;
String address="xxx.xxx.xxx.xxx";
int port=389;
//String bindDN="CN=name,CN=users,DC=mydomain,DC=com";
String bindDN="cn=Manager,dc=maxcrc,dc=com";
String password="secret";
boolean login_flag=true;
LDAPConnection c ;
AddRequest addRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt_login=(Button)findViewById(R.id.bt_login);
bt_login.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@SuppressLint("SimpleDateFormat") @Override
public void onClick(View arg0) {
try {
c= new LDAPConnection(address,port,bindDN,password);
c.setConnectionName("Demo Connection");
String con_name=c.getConnectionName();
long time=c.getConnectTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
String dateString = formatter.format(new Date(time));
Toast.makeText(getBaseContext(),"Connected to LDAP server....connection_name="+con_name+" at time"+dateString, Toast.LENGTH_LONG).show();
} catch (LDAPException e) {
login_flag=false;
e.printStackTrace();
Toast.makeText(getBaseContext(),"No connection was established" , Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
} finally{
if(login_flag){
c.close();
Toast.makeText(getBaseContext(), "Connection Closed successfully", Toast.LENGTH_LONG).show();
}
}
}
}
希望它可以帮助你。