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 = "www.usps.com"; 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() { @Override public 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 http://"+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 通信所用时间为:364ms
SSL 握手结束
加密套件为:TLS_RSA_WITH_AES_128_CBC_SHA
会话为:[Session-1, TLS_RSA_WITH_AES_128_CBC_SHA]
通信对方为:www.usps.com端口号:443
HTTP/1.0 400 Bad Request
Server: AkamaiGHost
Mime-Version: 1.0
Content-Type: text/html
Content-Length: 216
Expires: Thu, 26 Mar 2015 04:08:58 GMT
Date: Thu, 26 Mar 2015 04:08:58 GMT
Connection: 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>
原文:http://blog.csdn.net/soulofandroid/article/details/44648545