======Java中的SSL通信初步(1)======

package com.panpass.main;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.UnknownHostException;import javax.net.ssl.HandshakeCompletedEvent;import javax.net.ssl.HandshakeCompletedListener;import javax.net.ssl.SSLSocket;import javax.net.ssl.SSLSocketFactory;//http://blog.csdn.net/eclipsexys/article/details/44495285 LruCache/** * 客户端程序 * @author Administrator */public class HttpsClientTest {private String host = "";private int port = 443;private SSLSocketFactory sslSocketFactory = null;private SSLSocket sslSocket = null;public HttpsClientTest() throws UnknownHostException, IOException {super();sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();long sslStartTime = System.currentTimeMillis();sslSocket = (SSLSocket) sslSocketFactory.createSocket(host,port);long sslEndTime = System.currentTimeMillis();System.out.println("SSL 通信所用时间为:"+(sslEndTime-sslStartTime)+"ms");sslSocket.setEnabledCipherSuites(sslSocket.getEnabledCipherSuites());sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {@Overridepublic void handshakeCompleted(HandshakeCompletedEvent event) {System.out.println("SSL 握手结束");System.out.println("加密套件为:"+event.getCipherSuite());System.out.println("会话为:"+event.getSession());System.out.println("通信对方为:"+event.getSession().getPeerHost()+"端口号:"+event.getSession().getPeerPort());}});}public void communicate() throws IOException {StringBuffer sb = new StringBuffer("GET "+host+"/HTTP/1.1\r\n");sb.append("Host:"+host+"\r\n");sb.append("Accept: */*\r\n");sb.append("\r\n");// 发出Http请求OutputStream os = sslSocket.getOutputStream();os.write(sb.toString().getBytes());// 接受响应InputStream is = sslSocket.getInputStream();ByteArrayOutputStream abos = new ByteArrayOutputStream();byte[] bytes = new byte[1024];int len = -1;while ((len = is.read(bytes))!= -1) {abos.write(bytes, 0, len);}System.out.println(new String(abos.toByteArray()));sslSocket.close();}public static void main(String[] args) throws UnknownHostException, IOException {new HttpsClientTest().communicate();}}

输出结果:

SSL 通信所用时间为:364msSSL 握手结束加密套件为:TLS_RSA_WITH_AES_128_CBC_SHA会话为:[Session-1, TLS_RSA_WITH_AES_128_CBC_SHA]通信对方为:端口号:443HTTP/1.0 400 Bad RequestServer: AkamaiGHostMime-Version: 1.0Content-Type: text/htmlContent-Length: 216Expires: Thu, 26 Mar 2015 04:08:58 GMTDate: Thu, 26 Mar 2015 04:08:58 GMTConnection: close<HTML><HEAD><TITLE>Bad Request</TITLE></HEAD><BODY><H1>Bad Request</H1>Your browser sent a request that this server could not understand.<P>Reference #7.9a5732b8.1427342938.0</BODY></HTML>

,人生就像一杯没有加糖的咖啡,喝起来是苦涩的,

======Java中的SSL通信初步(1)======

相关文章:

你感兴趣的文章:

标签云: