The task is to implement a client, which would connect to a remote host using https protocol, and print on screen the html file. I can do it successfully by using http protocol, but when I add the ssl part, it can not work. the code is like below
Can someone help me? Many thanks.
Code:
import java.net.*;
import javax.net.ssl.*;
import java.security.*;
class ReadURL {
static final String TRUSTSTORE = "myStore.ks";
static final String TRUSTSTOREPASSWD = "12345";
public static void main(String[] args) throws IOException{
try {
SSLContext sslContext = SSLContext.getInstance( "TLS" );
KeyStore ts = KeyStore.getInstance("JCEKS");
ts.load(new FileInputStream(TRUSTSTORE), TRUSTSTOREPASSWD.toCharArray());
TrustManagerFactory tfm = TrustManagerFactory.getInstance("SunX509");
tfm.init(ts);
sslContext.init(null, tfm.getTrustManagers(), null );
SSLSocketFactory sslFact = sslContext.getSocketFactory();
SSLSocket client = (SSLSocket)sslFact.createSocket("localhost", 8082);
client.setEnabledCipherSuites( client.getSupportedCipherSuites() );
URL url = new URL("https://localhost:8082/");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
catch (Exception e) {
System.err.println("Communication error " + e);
e.printStackTrace();
}
}//end main
}//end class ReadURL
Comment