I am trying to connect to a URL from a my Android app in Andorid Version 4.1.1, and I get the error indicated in the Title of my question, but when I tried to connect the sa
This might happen because the CN (Common Name) you have declared on your SSL does not mach the actual URL you are sending your HTTP request too.
If so, create a new SSL and enter the currect CN. That should fix the problem.
In Kotlin:
fun HttpsURLConnection.trustCert() {
try {
//Accepts every hostname
this.hostnameVerifier = HostnameVerifier { hostname, _ ->
println(hostname) //To be hardcoded/as needed
true
}
val trustMgr:Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(certs: Array<out X509Certificate>?, authType: String?) {}
override fun checkServerTrusted(certs: Array<out X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate>? = null
})
this.sslSocketFactory = SSLContext.getInstance("TLS").also {
it.init(null, trustMgr, SecureRandom())
}.socketFactory
} catch (e: Exception) {
prinntln("SSL self-signed certificate processing error due to ${e.message}")
}
}
Usage:
val conn = URL(Uri.Builder().also {
it.scheme("https")
it.encodedAuthority("$serverIp:$serverPort")
}.build().toString()).openConnection() as HttpsURLConnection
conn.trustCert()
val respCode = conn.responseCode
if(respCode == 200) {
//do something (eg: read inputStream)
}
Android can't set up SSL connection, I suppose. Maybe your certificate for other host name, not the one you establish connection to. Read docs here and here.
it's possible that your problem is what your url's were resolved via "https". you must convert all string urls to "http" and it will work.
EDIT:
SchemeRegistry schemeRegistry = new SchemeRegistry ();
schemeRegistry.register (new Scheme ("http",
PlainSocketFactory.getSocketFactory (), 80));
schemeRegistry.register (new Scheme ("https",
new CustomSSLSocketFactory (), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager (
params, schemeRegistry);
return new DefaultHttpClient (cm, params);
CustomSSLSocketFactory:
public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory
{
private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory ();
public CustomSSLSocketFactory ()
{
super(null);
try
{
SSLContext context = SSLContext.getInstance ("TLS");
TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () };
context.init (null, tm, new SecureRandom ());
FACTORY = context.getSocketFactory ();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Socket createSocket() throws IOException
{
return FACTORY.createSocket();
}
// TODO: add other methods like createSocket() and getDefaultCipherSuites().
// Hint: they all just make a call to member FACTORY
}
FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager, yet none of the methods actually perform any work, get a sample [here][1].
Good Luck!