Service Side
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.Socket;
Import Java.security.KeyStore;
Import Javax.net.ssl.KeyManagerFactory;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.SSLServerSocket;
Import Javax.net.ssl.TrustManagerFactory; /************************************************************************************************************** * <ul> * <li>1) generate the server-side private key </li> * <li>keytool-genkey-alias Serverkey-keystore Kserv er.keystore</li> * <li>2) According to the private key, everywhere service-side Certificate </li> * <li>keytool-exoport-alias Serverkey-keystore k Server.keystore-file server.crt</li> * <li>3) to add certificates to the client trusted keystore </li> * <li>keytool-impo Rt-alias serverkey-file server.crt-keystore tclient.keystore</li> * </ul> ***************************** ******************************//** * SSL Server * * */public class Sslserver {Priv
ATE static final int default_port = 7777;
private static final String Server_key_store_password = "123456";
private static final String Server_trust_key_store_password = "123456";
Private Sslserversocket ServerSocket; /** * Start Program * * @param args/public static void main (string[] args) {Sslserver Server =
New Sslserver ();
Server.init ();
Server.start (); /** * <ul> * <li> listening to SSL Server socket</li> * <li> because the program is not demo Socket monitor, so simply using single line , and only accepts messages from the client, and returns the client-specified message </li> * </ul>/public void start () {if (ServerSocket = =
NULL) {System.out.println ("ERROR");
Return
} while (true) {try {Socket s = serversocket.accept (); InputStream input = S.getinputstream ();
OutputStream output = S.getoutputstream ();
Bufferedinputstream bis = new Bufferedinputstream (input);
Bufferedoutputstream BOS = new Bufferedoutputstream (output);
byte[] buffer = new BYTE[20];
Bis.read (buffer);
System.out.println (new String (buffer));
Bos.write ("Server Echo". GetBytes ());
Bos.flush ();
S.close ();
catch (Exception e) {System.out.println (e); /** * <ul> * <LI>SSL connection Focus:</li> * <li> initialization SSLSERVERSOCKET&L t;/li> * <li> Import service-side private key KeyStore, import server-side trusted keystore (client's certificate) </li> * </ul> */Public V
OID init () {try {Sslcontext ctx = sslcontext.getinstance ("SSL"); Keymanagerfactory KMF = keymanagerfactory.getinstance ("SuNX509 ");
Trustmanagerfactory TMF = trustmanagerfactory.getinstance ("SunX509");
KeyStore KS = keystore.getinstance ("JKS");
KeyStore tks = keystore.getinstance ("JKS");
Ks.load (New FileInputStream ("E:/kserver.keystore"), Server_key_store_password.tochararray ());
Tks.load (New FileInputStream ("E:/tserver.keystore"), Server_trust_key_store_password.tochararray ());
Kmf.init (KS, Server_key_store_password.tochararray ());
Tmf.init (TKS);
Ctx.init (Kmf.getkeymanagers (), tmf.gettrustmanagers (), NULL);
ServerSocket = (sslserversocket) ctx.getserversocketfactory (). Createserversocket (Default_port);
Serversocket.setneedclientauth (TRUE);
catch (Exception e) {e.printstacktrace (); }
}
}
Client
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.security.KeyStore;
Import Javax.net.ssl.KeyManagerFactory;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.SSLSocket;
Import Javax.net.ssl.TrustManagerFactory; /** * SSL Client * */public class Sslclient {private static final String Default_host = "127.
0.0.1 ";
private static final int default_port = 7777;
private static final String Client_key_store_password = "123456";
private static final String Client_trust_key_store_password = "123456";
Private Sslsocket Sslsocket; /** * Launch Client program * * @param args/public static void main (string[] args) {sslclient client
= new Sslclient ();
Client.init ();
Client.process (); /** * via SSL socket withServer to connect and send a message/public void process () {if (Sslsocket = null) {System.out.println ("Erro
R ");
Return
try {inputstream input = Sslsocket.getinputstream ();
OutputStream output = Sslsocket.getoutputstream ();
Bufferedinputstream bis = new Bufferedinputstream (input);
Bufferedoutputstream BOS = new Bufferedoutputstream (output);
Bos.write ("Client message". GetBytes ());
Bos.flush ();
byte[] buffer = new BYTE[20];
Bis.read (buffer);
System.out.println (new String (buffer));
Sslsocket.close ();
catch (IOException e) {System.out.println (e); }/** * <ul> * <LI>SSL connection Focus:</li> * <li> initialization sslsocket</li> * &
Lt;li> Import Client private key KeyStore, import client trusted KeyStore (server-side certificate) </li> * </ul>/public void init () {
try { Sslcontext CTX = sslcontext.getinstance ("SSL");
Keymanagerfactory KMF = keymanagerfactory.getinstance ("SunX509");
Trustmanagerfactory TMF = trustmanagerfactory.getinstance ("SunX509");
KeyStore KS = keystore.getinstance ("JKS");
KeyStore tks = keystore.getinstance ("JKS");
Ks.load (New FileInputStream ("E:/kclient.keystore"), Client_key_store_password.tochararray ());
Tks.load (New FileInputStream ("E:/tclient.keystore"), Client_trust_key_store_password.tochararray ());
Kmf.init (KS, Client_key_store_password.tochararray ());
Tmf.init (TKS);
Ctx.init (Kmf.getkeymanagers (), tmf.gettrustmanagers (), NULL);
Sslsocket = (sslsocket) ctx.getsocketfactory (). Createsocket (Default_host, Default_port);
catch (Exception e) {System.out.println (e); }
}
}
http://blog.csdn.net/xxb2008
java call HTTPS link
Import javax.net.ssl.*;
Import java.io.*;
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.security.KeyStore;
Import Java.security.SecureRandom;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;
/** * Created with. * date:14-4-10 * Time: PM 3:09 * To change this template use File | Settings |
File Templates. */public class Sslhttpclient {public static void main (string[] args) {sslhttpclient client = new Sslhtt
Pclient ();
Client.connect ();
private void Connect () {sendpost ("https://localhost/index.jsp", "name1=value1&name2=value2"); /** * Request * Sending the Post method to the specified URL * @param URL to send the requested URL * @param params request parameter, the request parameter should be name1=value1&am
The form of p;name2=value2. * Response to remote resource on behalf of @return URL/public static string Sendpost (string url, string params) {PrintWriter out = n
ull;
BufferedReader in = null;
String result = "";try {URL realurl = new URL (URL);
Sslcontext context = sslcontext.getinstance ("SSL");
Context.init (NULL, New Trustmanager[]{new Trustanytrustmanager ()}, New SecureRandom ());
Httpsurlconnection conn = (httpsurlconnection) realurl.openconnection (); conn = (httpsurlconnection) realurl.openconnection ();
The connection between open and URL conn.setsslsocketfactory (context.getsocketfactory ());
Conn.sethostnameverifier (New Trustanyhostnameverifier ());
Sets the common request attribute Conn.setrequestproperty ("accept", "*/*");
Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;
SV1) ");
The Send POST request must be set to the following two lines conn.setdooutput (true);
Conn.setdoinput (TRUE);
Gets the output stream of the URLConnection object = new PrintWriter (Conn.getoutputstream ());
Send Request parameters Out.print (params);
Flush output Stream Buffer Out.flush ();
Defines the response of the BufferedReader input stream to read the URL in = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));
String Line;
while (line = In.readline ())!= null} {result = "\ n" + line;
} System.out.println (Result); catch (Exception e) {System.out.println ("send post request exception.)
"+ e);
E.printstacktrace ();
///Use finally block to close output stream, input stream finally {try {if (out!= null) {
Out.close ();
} if (in!= null) {in.close ();
} catch (IOException ex) {ex.printstacktrace ();
} return result; The class Trustanytrustmanager implements X509trustmanager {public void checkclienttrusted (x509certificate[) chain, STring AuthType) throws certificateexception {} public void checkservertrusted (x509certificate[) Chai
N, String authtype) throws certificateexception {} public x509certificate[] Getacceptedissuers () {
return new x509certificate[]{}; } class Trustanyhostnameverifier implements Hostnameverifier {public boolean verify (String hostname, sslsession s
ession) {//Direct pass, full trust return true;
}
}