0

我正在尝试运行一个示例程序,该程序在getCipherSuite()调用java.lang.IllegalStateException: connection not yet open exception. 连接是打开的,所以不知道为什么会这样。我正在使用 java 版本 1.6.0_18

有谁知道为什么这是异常引发?

谢谢。

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);
  }

}
4

1 回答 1

1

正是由于例外中所述的原因而发生的。您在 cnnextion 打开之前调用它。解决方法:在调用getInputStream()、getResponseCode()等之后调用。

于 2013-09-16T19:28:55.490 回答