Ryan Newman
Ryan Newman

Reputation: 856

HttpUrlConnection isn't contacting server

I am trying to connect to a server to create a new account. I am capturing the full URL into a string for debugging purposes, and then setting the URL to that string and trying to open that connection. When I copy and paste the URL into my browser, I get a response back and the proper execution. However, in my app I'm not getting a response, or even my toast notifications popping up. Am I doing something wrong?

private void postAPI(String userName, String password, String emailAddres, String firstName,
                     String lastName, String phone, String officeName, String address,
                     String city, String state, String zip, String salesRep) {
    final String tempAddress = ("https://www.exampleAddress.com/mobilenewacct.asp?u=" +
            userName + "&p=" + password + "&email=" + emailAddres + "&fname=" + firstName +
            "&lname=" + lastName + "&phone=" + phone + "&agoffice=" + officeName +
            "&agaddress=" + address + "&agcity=" + city + "&agstate=" + state +
            "&agzip=" + zip + "&repid=" + 1296).replace("@", "atsign");

    new AsyncTask<Void, Void, Boolean>(){
        @Override
        protected Boolean doInBackground(Void... params){
            try {
                url = new URL(tempAddress);

                urlConnection = (HttpURLConnection) url.openConnection();

                Log.v("Connection Open", "Open");

                urlConnection.connect();

                Log.v("Connection Connected", "Connected");

            } catch (Exception e) {
                //ERROR
                e.printStackTrace();
            } finally {
                try {
                    urlConnection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
        @Override
        public void onPostExecute(Boolean result){
            //Some message that indicates the connection was finished, or nothing.
        }
    }.execute();
}

Logcat Output

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:322)
W/System.err﹕ at com.android.okhttp.Connection.upgradeToTls(Connection.java:201)
W/System.err﹕ at com.android.okhttp.Connection.connect(Connection.java:155)
W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
W/System.err﹕ at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
W/System.err﹕ at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
W/System.err﹕ at com.octitle.ryann.octmobile.NewUserActivity$2.doInBackground(NewUserActivity.java:133)
W/System.err﹕ at com.octitle.ryann.octmobile.NewUserActivity$2.doInBackground(NewUserActivity.java:123)
W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
W/System.err﹕ Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err﹕ at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:318)
W/System.err﹕ at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:219)
W/System.err﹕ at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:114)
W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:550)
W/System.err﹕ at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:318)
W/System.err﹕ ... 16 more
W/System.err﹕ Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err﹕ ... 22 more

Upvotes: 3

Views: 1259

Answers (2)

William Hu
William Hu

Reputation: 16149

I used this in kotlin:

private fun configureHttps() {
        val ctx = SSLContext.getInstance("TLS")
        val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
            override fun getAcceptedIssuers(): Array<X509Certificate?> {
                return arrayOfNulls(0)
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(
                chain: Array<X509Certificate>,
                authType: String
            ) {
            }

            @Throws(CertificateException::class)
            override fun checkClientTrusted(
                chain: Array<X509Certificate>,
                authType: String
            ) {
            }
        })
        val hostnameVerifier =
            HostnameVerifier { hostname, session ->
                true
            }

        ctx.init(null, trustAllCerts, null)
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.socketFactory)
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier)
    }

Upvotes: 1

Ryan Newman
Ryan Newman

Reputation: 856

I ended up adding this to my code before I tried opening the connection until I can ask the developer who designed the server about whether or not the certificate is self signed or not

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] {
new X509TrustManager() {
     public void checkClientTrusted(X509Certificate[] chain, String authType) {}
     public void checkServerTrusted(X509Certificate[] chain, String authType) {}
     public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; }
     }
}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
     public boolean verify(String hostname, SSLSession session) {
          return true;
     }
});

Found here

HTTPS GET (SSL) with Android and self-signed server certificate

Upvotes: 2

Related Questions