简体   繁体   中英

java https networking issue

I'm trying to implement simplest HTTPS communication program. There are a lot of examples on the web, but I fail to run them successfully.
Here is one example:

public class ReadHttpsURL1 {
   static final int HTTPS_PORT = 443; 

   public static void main(String argv[]) throws Exception {
       String url = "www.sun.com";
       System.setProperty("java.net.useSystemProxies", "true");

      SocketFactory factory = SSLSocketFactory.getDefault(); 

      Socket socket = factory.createSocket(url, HTTPS_PORT); 

      BufferedWriter out = new BufferedWriter(new 
            OutputStreamWriter(socket.getOutputStream()));
      BufferedReader in = new BufferedReader(
        new InputStreamReader(socket.getInputStream()));
      out.write("GET / HTTP/1.0\n\n");
      out.flush();

      String line;
      StringBuffer sb = new StringBuffer();
      while((line = in.readLine()) != null) {
         sb.append(line);
      }
      out.close();
      in.close();
      System.out.println(sb.toString());
   }
}

It hangs up for a time about a minute (I believe due to server-side timeout) and fail with error. Hangs up on

Socket socket = factory.createSocket(url, HTTPS_PORT); 

Error is

Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocksSocketImpl.readSocksReply(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.<init>(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl.createSocket(Unknown Source)
    at com.sun.ex1.ReadHttpsURL1.main(ReadHttpsURL1.java:20)

Here is second example:

public class HttpsTest {

    public static void main(String[] args) throws MalformedURLException, IOException {
        System.setProperty("java.net.useSystemProxies", "true");

        URL url = new URL("https://www.sun.com");
        URLConnection con = url.openConnection();
        con.setAllowUserInteraction(true);
        InputStream is = new BufferedInputStream(con.getInputStream());
        for (int b = is.read(); b >= 0; b = is.read()) {
            System.out.write(b);
        }
    }
}

Just throw this exception:

Exception in thread "main" javax.net.ssl.SSLKeyException: RSA premaster secret error
    at com.sun.net.ssl.internal.ssl.RSAClientKeyExchange.<init>(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverHelloDone(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at HttpsTest.main(HttpsTest.java:16)
Caused by: java.security.NoSuchAlgorithmException: SunTlsRsaPremasterSecret KeyGenerator not available
    at javax.crypto.KeyGenerator.<init>(DashoA13*..)
    at javax.crypto.KeyGenerator.getInstance(DashoA13*..)
    at com.sun.net.ssl.internal.ssl.JsseJce.getKeyGenerator(Unknown Source)
    ... 14 more

I've read a bit about NoSuchAlgorithmException . This seems to be related with sunjce_provider.jar
I've tried different variants to include this file in the classpath and even make application dependency to this jar (jar was present in classpath for sure)

HTTPS URL is live URL. Proxy settings are working (it throws a different connection exception otherwise).
java version "1.6.0_23"

Are these errors related?
Any ideas how to fix?
Thanks for help!

I type the above code on my Eclipse IDE, and it runs well. I think one problem that you may encounter is with your proxy server .

The response was:

HTTP/1.1 301 Moved Permanently
Server: Sun-Java-System-Web-Server/7.0
Date: Fri, 25 Feb 2011 11:52:30 GMT
P3p: policyref="http://www.sun.com/p3p/Sun_P3P_Policy.xml", CP="CAO DSP COR CUR ADMa DEVa TAIa PSAa PSDa CONi TELi OUR  SAMi PUBi IND PHY ONL PUR COM NAV INT DEM CNT STA POL PRE GOV"Location: http://www.oracle.com/us/sun
Content-length: 0
Connection: close

What I changed from your code was only this snippet:

System.setProperty("java.net.useSystemProxies", "false");

Just my guess:

  • your network there actually doesn't use proxy but you turned it on, or
  • your proxy doesn't support HTTPS or
  • your proxy HTTPS support for your user is disabled (either intentionally or unintentionally).

was:

If you are not intended to write a low level library... How about using [Http Components from Apache][1]?

[1]: http://hc.apache.org/index.html

Issue with sockets was caused by proxy. I've wrong concluded if I don't get java.net.ConnectException: Connection refused: connect (in case proxy is not configured at all) proxy should not cause issue. In a 'guest network' (without proxy) application appeared to be working. As it turned out proxy had different configuration for each protocol and my company policy deprecate raw sockets connections.

Did you write this code yourself or copy it from somewhere? I only ask because it is not the way I usually make a HTTPS connection. The first thing I'd do when testing HTTPS is find server that will respond to a HTTPS request. www.sun.com will redirect to an Oracle page and while this is still valid it is possibly not what you want.
I can't be 100% sure on the first but I suspect you're suffering from either a blocking read or write. Debugging could help.
The only time I have seen that stack trace was when the JCE classes for Java 5 and 6 were mixed up and the Java version couldn't cope. The same code in HttpsTest "works for me"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM