天天看點

HttpsUrlConnection https雙向驗證

以下文章都是整合了好多網上的好多朋友的優秀資源,才寫出來的。具體參考過誰的,我也記不清楚了。關于怎麼生成https雙向的證書,位址在這裡:

http://www.blogjava.net/stevenjohn/archive/2012/08/22/385989.html  

應該正常來說,按照這個教程做的話是沒有任何問題的,但是也有些朋友出過問題,主要問題是在,把證書導入到浏覽器裡面的時候出的,注意這裡。

我這裡面的我都做過三四次了,基本沒啥問題。但也不排除不會不出問題。

由于網上關于httpCilent來測試調用HTTPS的例子較少,經過在度娘和谷爹的查找,總算是也找到了一篇文章,參考以後,做出來一個測試類,在我機器上面是能夠跑通的。具體位址: http://www.blogjava.net/stevenjohn/archive/2012/09/27/388646.html  

//首先說一下,這個是我随便寫的一個釋出到tomcat的httpsUrlConnection的Servlet服務,主要是用來測試一下https雙向驗證的,現在網上好多的文章都是https單向驗證的Java代碼,我在網上看過好多,但是好多都是半成品,然後總結了一下,在自己的機器上面是完全能夠跑通的,在這裡做個筆記,以後用得着的時候來拿:

package com.abin.lee.https; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class ReceiveHttpsUrlConnectionRequest extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("receive https request");

                 BufferedReader reader=new BufferedReader(new InputStreamReader(request.getInputStream())); String line=null; StringBuffer stb=new StringBuffer();

                //循環的一行一行的讀取内容

     while((line=reader.readLine())!=null){ stb.append(line); }

                //列印讀取到的内容。 System.out.println("stb="+stb.toString());

                //給調用者傳回内容 PrintWriter write=response.getWriter(); write.write("receive HttpsUrlConnection success"); write.flush(); write.close(); } }

//這個是在web工程裡面的web.xml裡面配置的釋出的servlet服務

//web.xml

<servlet> <servlet-name>httpsUrlConnectionRequest</servlet-name> <servlet-class>com.abin.lee.https.ReceiveHttpsUrlConnectionRequest</servlet-class> </servlet> <servlet-mapping> <servlet-name>httpsUrlConnectionRequest</servlet-name> <url-pattern>/httpsUrlConnectionRequest</url-pattern> </servlet-mapping>

//HttpsUrlConnection測試類

package com.abin.lee.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.util.Date; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; public class HttpsUrlConnectionClient extends TestCase { // 用戶端密鑰庫 private String sslKeyStorePath; private String sslKeyStorePassword; private String sslKeyStoreType; // 用戶端信任的證書 private String sslTrustStore; private String sslTrustStorePassword;

        //上面釋出的servlet請求位址 private String httpsUrlConnectionUrl = "https://localhost:8443/global/httpsUrlConnectionRequest"; @Before public void setUp() {

                //這是密鑰庫

     sslKeyStorePath = "D:\\home\\tomcat.keystore"; sslKeyStorePassword = "stevenjohn"; sslKeyStoreType = "JKS"; // 密鑰庫類型,有JKS PKCS12等

                //信任庫,這裡需要服務端來新人用戶端才能調用,因為這個我是配置的https雙向驗證,不但是要用戶端信任服務端,服務端也要信任用戶端。 sslTrustStore = "D:\\home\\tomcat.keystore"; sslTrustStorePassword = "stevenjohn"; System.setProperty("javax.net.ssl.keyStore", sslKeyStorePath); System.setProperty("javax.net.ssl.keyStorePassword", sslKeyStorePassword); System.setProperty("javax.net.ssl.keyStoreType", sslKeyStoreType); // 設定系統參數 System.setProperty("javax.net.ssl.trustStore", sslTrustStore); System.setProperty("javax.net.ssl.trustStorePassword", sslTrustStorePassword); System.setProperty("java.protocol.handler.pkgs", "sun.net.www.protocol"); } @Test public void testHttpsUrlConnectionClient() { try { URL url = new URL(httpsUrlConnectionUrl);

                        //對于主機名的驗證,因為配置伺服器端的tomcat.keystore的證書的時候,是需要填寫使用者名的,一般使用者名來說是本地ip位址,或者本地配置的域名

     HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv);

                        //編寫HttpsURLConnection 的請求對象,這裡需要注意HttpsURLConnection 比我們平時用的HttpURLConnection對了一個s,因為https是也是遵循http協定的,并且是采用ssl這個安全套接字來傳輸資訊的,但是也有可能遭到黑客的攻擊   HttpsURLConnection connection = (HttpsURLConnection) url .openConnection(); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.setDoInput(true);

                        //設定請求方式為post,這裡面當然也可以用get,但是我這裡必須用post

     connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setReadTimeout(30000); String user="abin"; String pwd="abing"; String request="user="+user+"&pwd="+pwd; OutputStream out = connection.getOutputStream();

                        //下面的這句話是給servlet發送請求内容 out.write(request.getBytes()); out.flush(); out.close(); //接收請求的傳回值 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer stb = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { stb.append(line); } Integer statusCode = connection.getResponseCode(); System.out.println("傳回狀态碼:" + statusCode); reader.close(); connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }

//釋出好了服務,你需要在tomcat裡面配置好了https服務的端口才能使用。

//tomcat配置檔案:

 <Connector port="6060" protocol="HTTP/1.1"                 connectionTimeout="20000"                 redirectPort="8443" />

        <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"    SSLEnabled="true" maxThreads="150" scheme="https"    secure="true" clientAuth="true" sslProtocol="TLS"    keystoreFile="D:\\home\\tomcat.keystore" keystorePass="stevenjohn"  //密鑰庫    truststoreFile="D:\\home\\tomcat.keystore" truststorePass="stevenjohn" />//信任庫

繼續閱讀