Paul
Paul

Reputation: 111

Error calling HttpsURLConnection.getCipherSuite()

I'm trying to run an example program that's failing in the call to getCipherSuite() with a java.lang.IllegalStateException: connection not yet open exception. The connection is open so not sure why this is happening. I'm using java version 1.6.0_18

Does anybody know why this is exception is raising?

Thanks.

package web.services.https;

import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
import java.security.cert.Certificate;
import java.io.IOException;

public class SunClient {

  private static final String url_s = "https://java.sun.com:443";

  public static void main(String[] args) {
    new SunClient().do_it();
  }

  private void do_it() {

    try {
        URL url = new URL(url_s);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.connect();

        System.out.println("\nConnected ...\n");

        dump_features(conn);
    }

    catch(MalformedURLException e) {
        System.err.println("MalformedURLException exception: " + e);
    }

    catch(IOException e) {
        System.err.println("IOException exception: " + e);
    }

  }

  private void dump_features(HttpsURLConnection conn) {

    try {

        Certificate[] certs = conn.getServerCertificates();

        for(Certificate cert: certs) {
            print("\tCert. type: " + cert.getType());
            print("\tHash code: " + cert.hashCode());
            print("\tAlgorithm: " + cert.getPublicKey().getAlgorithm());
            print("\tFormat: " + cert.getPublicKey().getFormat());
            print("");
        }

        print("Status code: " + conn.getResponseCode());
        print("Cipher suite: " + conn.getCipherSuite());

    }

    catch(Exception e) {
        System.err.println("Exception exception: " + e);
    }

  }

  private void print(String s) {
    System.out.println(s);
  }

}

Upvotes: 0

Views: 1707

Answers (1)

user207421
user207421

Reputation: 310913

It is happening for exactly the reason stated in the exception. You are calling it before the cnnextion is open. Solution: call it after, i.e. after calling getInputStream(), getResponseCode(), etc.

Upvotes: 1

Related Questions