JSSE和gnutls配合来实现Java和C的安全通信 (六)

2014-11-24 11:44:55 · 作者: · 浏览: 35
intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/

import java.net.*;
import java.security.KeyStore;
import java.io.*;
import javax.net.ssl.*;

/*
* This example demostrates how to use a SSLSocket as client to
* send a HTTP request and get response from an HTTPS server.
* It assumes that the client is not behind a firewall
*/

public class JavaEchoClient {

public static void main(String[] args) throws Exception {
try {
char[] passphrase = "passphrase".toCharArray();

KeyStore ksTrust = KeyStore.getInstance("JKS");
ksTrust.load(new FileInputStream("truststore.jks"), passphrase);

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ksTrust);

SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, tmf.getTrustManagers(), null);

SSLSocketFactory factory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket("10.74.125.141", 5556);

/*
* send http request
*
* Before any application data is sent or received, the
* SSL socket will do SSL handshaking first to set up
* the security attributes.
*
* SSL handshaking can be initiated by either flushing data
* down the pipe, or by starting the handshaking by hand.
*
* Handshaking is started manually in this example because
* PrintWriter catches all IOExceptions (including
* SSLExceptions), sets an internal error flag, and then
* returns without rethrowing the exception.
*
* Unfortunately, this means any error messages are lost,
* which caused lots of confusion for others using this
* code. The only way to tell there was an error is to call
* PrintWriter.checkError().
*/
socket.startHandshake();

PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())));

out.println("I love Baomin Wang");
out.println();
out.flush();

/*
* Make sure there were no surprises
*/
if (out.checkError())
System.out.println(
"SSLSocketClient: java.io.PrintWriter error");

/* read response */
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));

String inputLine;
inputLine = in.readLine();
System.out.println(inputLine);
/*
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
*/

in.close();
out.close();
socket.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}