Android https server connection No peer - android

I'm developing android application, which connecting to server via https connection.
I've created my_store.bks file with trusted sertificate and using following code to connect to server :
DefaultHttpClient httpclient = new DefaultHttpClient();
KeyStore trustStore = KeyStore.getInstance("BKS");
InputStream in = context.getResources().openRawResource(R.raw.my_store);
try{
trustStore.load(in,pass.toCharArray());
}
catch(Exception e){
Log.v("MyLog", "errror reading sert: " + e.toString());
}
finally{
in.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", socketFactory, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
HttpPost poster = new HttpPost(serverAdress);
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(formparams,"UTF-8");
poster.setEntity(ent);
HttpResponse responsePost = httpclient.execute(poster);
but when I'm executing this code, I've got next error:
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate No peer certificate
here is some similar problem
No peer cert. Not sure which route to take but i don't want ignore SSL certificates.
Does anyone know what it may be? May it be some server error? (server is developing, so may have errors, but in browser it works fine with sert).

Related

No peer certificate error on android 2.3 devices but working fine on android 4+

I have created the bks file for my server's certificate. This was added in the project's sources in raw folder
I've created my https client as follows:
public class MyHttpsClient extends DefaultHttpClient {
final Context context;
public MyHttpsClient(Context context) {
this.context = context;
}
#Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "testpassword".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
Then I use it like:
DefaultHttpClient httpClient = new MyHttpsClient(context);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(new StringEntity(jsonString));
response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
httpresponse = getResponse(entity);
Now here comes the funny part. This works just fine on android 4+ both real devices and emulator. THIS fails on android 2.3 with
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
How can I make it work on android 2.3 without the known "trust all certificates" way ?
A few days age i solved same problem. The solution consisted in the following. I take all certificates installed on device(in my case it was samsung galaxy II) and go to the server side developer, who manage certificate chain installed on server. He analyzes ssl chain and detected that in chain there is one certificate (Thawte 2006) and other certificate (Thawte 2010). He removed oldest certificate, which issued in 2006, and ssl verification on android 2.x become working. I suggest you, before trying to get work local keystore, research your server side ssl chain and check that this chain doesn't have unnecessary certificates, because android 2.x devices cannot ignore not necessary certificates, but other platforms 3.x 4x and ios, windows phone can do it, i mean ignore "trash" in ssl certificate chain.

Getting SSLPeerUnverifiedException in Android

i am getting SSL Peer Unverified Exception when i try to connect using HTTPs Connection.
I am new to HTTPs.
My code is :
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpPost httppost = new HttpPost("https://server.example.com/Login");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("LoginId",uname));
nameValuePairs.add(new BasicNameValuePair("Password",pass));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
}
Log.i("zacharia", "Response :"+EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
}
The SSL Peer Unverified Exception could be thrown for several reasons, the most common is when the certificate sent by the server is a self signed certificate and not a certificate signed by authorized CA, if that's the issue the common approach in android is adding the certificate to the Trusted Certificates chain and then making the request as follows:
KeyStore selfsignedKeys = KeyStore.getInstance("BKS");
selfsignedKeys.load(context.getResources().openRawResource(R.raw.selfsignedcertsbks),
"genericPassword".toCharArray());
TrustManagerFactory trustMgr = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustMgr.init(selfsignedKeys);
SSLContext selfsignedSSLcontext = SSLContext.getInstance("TLS");
selfsignedSSLcontext.init(null, trustMgr.getTrustManagers(), new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(selfsignedSSLcontext.getSocketFactory());
URL serverURL = new URL("https://server.example.com/endpointTest");
HttpsURLConnection serverConn = (HttpsURLConnection)serverURL.openConnection();
Take on count that this approach is only when you are sure the certificate not signed by a CA, and in order to make it work you need to have the certificate it self, put it in a BKS keystore (for android to read it) and then open an HttpURLConnection using the SSL context that "accepts" that self signed certificate, because the DefaultHttpClient will not handle those requests based on the Default SSLContext.
If you want to learn more about SSL i recommend you to read the book "Application Security for the Android Platform" by Jeff Six Editorial O'Reilly...
Regards!

SSL connection reuse with Android HttpClient

I'm developing a secure web service between my self-implemented java web proxy (that forwards requests to the actual web service) and an android application.
Doing so with standard (insecure) http connections works perfectly well. Now I want to use a secure (SSL) connection between the proxy and the android client.
This works as long as I instantiate a new HttpClient for each request, which is beside wasting resources extremely slow as I'm is doing a two way handshake for each request.
So I'm trying to reuse the HttpClient for each request which results for secure connections in the following exception
java.lang.IllegalStateException: Connection already open.
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:150)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
When I change my proxy and the client to no-ssl communication it works without any problems.
Does anybody know what I'm doing wrong? Thanks a lot for your help!
By the way the server code is totally similar except using SSLServerSocket with loaded certificates instead of using ServerSocket.
Client parameter setup
// Set basic data
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams.setUserAgent(params, "Android app/1.0.0");
// Make pool
ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
ConnManagerParams.setMaxTotalConnections(params, 20);
// Set timeout
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Some client params
HttpClientParams.setRedirecting(params, false);
Http client creation
// load truststore certificate
InputStream clientTruststoreIs = context.getResources().openRawResource(R.raw.server);
KeyStore trustStore = KeyStore.getInstance("BKS");
trustStore.load(clientTruststoreIs, "server".toCharArray());
// initialize trust manager factory with the read truststore
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
// setup client certificate
// load client certificate
InputStream keyStoreStream = context.getResources().openRawResource(R.raw.client);
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(keyStoreStream, "client".toCharArray());
// initialize key manager factory with the read client
// certificate
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "client".toCharArray());
// initialize SSLSocketFactory to use the certificates
SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "client", trustStore, null, null);
// Register http/s shemas!
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("https", socketFactory, port));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
httpClient = new DefaultHttpClient(conMgr, params);
Client request execution
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
in = entity.getContent();
String result = convertStreamToString(in);
in.close();
I have this exact same issue with Android and HttpClient - it only seems to manifest itself when using a client-side certificate, just like you have. Remove client auth and it works fine, haven't found a workaround as of yet.
Edit:
Enable stale connection checking.
HttpConnectionParams.setStaleCheckingEnabled(params, true);
Fixed it for me.
Are you using a thread-safe connection manager? If not, that may be the problem if you're using the same HttpClient in multiple threads.
This article has details: http://candrews.integralblue.com/2011/09/best-way-to-use-httpclient-in-android/

'No peer certificate' error in Android 2.3 but NOT in 4

Getting the "javax.net.ssl.SSLPeerUnverifiedException: No peer certificate error" in an emulator running Android 2.3 but NOT in 4. In 4 it works perfectly. I'm trying to connect to a live server via https. It uses a valid Thawte certificate, works fine in all browsers and Android 3 and 4.
If anyone has code help, PLEASE and thanks. Also, if anyone has any suggestions on a secure workaround, I'd appreciate it. I'm still learning, and I've been on this problem for a week. It has to end, so I can continue working and learning. Urgh.
Here is HttpCLient code, courtesy Antoine Hauck (http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/):
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
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.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import android.content.Context;
public class MyHttpClient extends DefaultHttpClient {
final Context context;
public MyHttpClient(Context context) {
this.context = context;
}
#Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = context.getResources().openRawResource(R.raw.my_cert);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "my_pass".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
And here is the code that instantiates it:
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpPost post = new HttpPost(server_login_url);
List <NameValuePair> parameters = new ArrayList <NameValuePair>();
parameters.add(new BasicNameValuePair("username", user));
parameters.add(new BasicNameValuePair("password", pass));
try {
post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
Log.d(DEBUG_TAG, "in UnsupportedEncodingException - " + e2.getMessage());
e2.printStackTrace();
}
// Execute the GET call and obtain the response
HttpResponse getResponse = null;
try {
getResponse = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// Toast.makeText(getBaseContext(),message,Toast.LENGTH_LONG).show();
Log.d(DEBUG_TAG, "in ClientProtocolException - " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
// Toast.makeText(getBaseContext(),message,Toast.LENGTH_LONG).show();
Log.d(DEBUG_TAG, "in client.execute IOException - " + e.getMessage());
e.printStackTrace();
}
The error is caught in the IOException block. Here is the stack:
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:258)
org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:164)
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
org.ffb.tools.SplashActivity$LoginTask.makeConnection(SplashActivity.java:506)
org.ffb.tools.SplashActivity$LoginTask.doLogin(SplashActivity.java:451)
org.ffb.tools.SplashActivity$LoginTask.doInBackground(SplashActivity.java:439)
org.ffb.tools.SplashActivity$LoginTask.doInBackground(SplashActivity.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:185)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
java.util.concurrent.FutureTask.run(FutureTask.java:138)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
java.lang.Thread.run(Thread.java:1019)
Here is the chain order (from openssl command):
The chain looks good I think.
i:/C=US/O=Thawte, Inc./OU=Domain Validated SSL/CN=Thawte DV SSL CA
1 s:/C=US/O=Thawte, Inc./OU=Domain Validated SSL/CN=Thawte DV SSL CA
i:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2006 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA
2 s:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2006 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA
i:/C=ZA/ST=Western Cape/L=Cape Town/O=Thawte Consulting cc/OU=Certification Services Division/CN=Thawte Premium Server CA/emailAddress=premium-server#thawte.com
This thread was really helpful when I debugged a similar issue.
Summary Android 2.3 HTTPS/SSL checklist:
If your CA is in Android's 2.3 list of trusted CA's -- and Thawte is -- there's no need to include the certificate in the app.
Android 2.3 does not support Server Name Indication so if your server is relying on it for SSL handshaking, Android may not be getting the certificates you're expecting.
Do you have certificate chain on the server installed, and is it ordered correctly? Most browsers handle out-of-order certificate chains but Android 2.3 does not. bdc's answer in the thread I mentioned above describes how to check the validity of your SSL certificate and chain with "openssl s_client -connect yourserver.com:443".
When digging up that old 2.3 device you have in your bottom drawer, please ensure its date and time are set correctly after being powerless for too long.
I had exactly the same issue as you. Everything was working fine with android >3.X but when I tried with some (but not all !) 2.3.X devices I got that famous "No peer certificate error" exception.
I dug a lot through stackoverflow and other blogs but I haven't found anything that worked on those "rogue" devices (in my case: correct use of truststore; no sni required; correct cert chain order on server; etc ...).
It's look like that android's Apache HttpClient was just not working correctly on some 2.3.X devices.
The "no peer certificates" exception was occurring too early to even reach a custom hostname verifier code, so solution like that one were not working for me.
Here was my code :
KeyStore trustStore = KeyStore.getInstance("BKS");
InputStream is = this.getAssets().open("discretio.bks");
trustStore.load(is, "discretio".toCharArray());
is.close();
SSLSocketFactory sockfacto = new SSLSocketFactory(trustStore);
sockfacto.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", sockfacto, 443));
SingleClientConnManager mgr = new SingleClientConnManager(httpParameters, schemeRegistry);
HttpClient client = new DefaultHttpClient(mgr, httpParameters);
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
So I rewrote everything using javax.net.ssl.HttpsURLConnection and now it's working on all devices I have tested (from 2.3.3 to 4.X).
Here is my new code :
KeyStore trustStore = KeyStore.getInstance("BKS");
InputStream is = this.getAssets().open("discretio.bks");
trustStore.load(is, "discretio".toCharArray());
is.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
URL request = new URL(url);
HttpsURLConnection urlConnection = (HttpsURLConnection) request.openConnection();
//ensure that we are using a StrictHostnameVerifier
urlConnection.setHostnameVerifier(new StrictHostnameVerifier());
urlConnection.setSSLSocketFactory(context.getSocketFactory());
urlConnection.setConnectTimeout(15000);
InputStream in = urlConnection.getInputStream();
//I don't want to change my function's return type (laziness) so I'm building an HttpResponse
BasicHttpEntity res = new BasicHttpEntity();
res.setContent(in);
HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, urlConnection.getResponseCode(), "");
resp.setEntity(res);
Certificate chain and hostname validation are working (I tested them).
If anyone want to take a better look on the change, here is a diff
Comments are welcome, I hope it will help some people.
Another source of this message can be an invalid date/time setting, e.g. when using a device which has gone a few months without power. Quite trivial, but it can be hard to spot.
What certificates are you loading from R.raw.my_cert? This error either speaks to having a misconfigured server -- not installing Thawte's primary and secondary intermediate CAs -- or you not loading and trusting the correct certificate chain.
Certificate verification (or more precisely - chain building) logic in (at least) Android 2.3 is faulty.
Here is what I have observed:
If the TLS server in it's certificate chain provides only server's certificate (non-selfsigned or selfsigned), then you can put server's certificate in keystore and verification will succeed.
If the TLS server in it's certificate chain provides also intermediate CA certificate, then in the keystore you must put only root CA certificate and make sure that the keystore does NOT contain server's and intermediate CA certificates (otherwise the verification will fail randomly).
If the TLS server in it's certificate chain provides intermediate and root CA certificates in the correct order, then you just have to make sure that root CA certificate is in the keystore (doesn't matter if server's and intermediate CA certificates are there).
So the "correct/reliable" way how to handle this is to include in the keystore only root CA certificates and blame server configuration for "No peer certificate" - in case server's certificate chain does not provide intermediate CA certificates or certificates are in incorrect order. You can test server using https://www.ssllabs.com/ssltest/.

How can I connect to an Http server with Basic Auth over SSL on Android?

I know this question has been asked before but none of the answers I have found are helping me. I am trying to connect to a simple login service over SSL with Basic Http Auth. The service is hosted at https://localhost:8443/login. When I hit the service from a browser (on windows, OSX, and Android) it works fine, I put in my username and password and I am authenticated properly. However, when I try to do this through code on my Xoom I get a ClientProtocolException that says "the server failed to respond with a valid HTTP response". Can anyone give me a push in the right direction? Here is my code
String result = null;
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
DefaultHttpClient client = new DefaultHttpClient(conMgr, params);
HttpGet get = new HttpGet(preferences.getString(getString(R.string.Security_Login_URL),
"https://localhost:80/login"));
String credentials = Base64.encodeToString((username + ":" + password).getBytes(), Base64.URL_SAFE);
if(credentials!=null){
get.addHeader("Authorization","Basic "+credentials);
ResponseHandler responseHandler=new BasicResponseHandler();
try {
result = client.execute(get, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Two common problems could cause this:
You should not do the BASIC authentication yourself. The Apache HttpClient has all the functionalities already included to do the BASIC authentication. Look either Basic Authentication or Preemptive BASIC authentication
Does your android device trusts the certificate from the server? When your browser trusts the cert, it doesn't mean that your device is also trusting it. Android has a very limited list of trusted certification authorities. You could check this from your device, when you visit the site on your Android built-in browser. If no warning message appears, everything should be OK. For further information about trusting additional certificates from an android device, you can look at my blog article.
Enjoy

Categories

Resources