Java https请求 HttpsURLConnection

有关tomcat 6.0如何配置https服务的文章可以参考:http://blog.csdn.net/zhou_zion/article/details/6759171

以下主要讲解如何使用https发起post请求:

参考文档:梁栋前辈的《Java加密与解密的艺术》

[java]  view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStreamReader;  
  5. import java.net.MalformedURLException;  
  6. import java.net.URL;  
  7. import java.security.GeneralSecurityException;  
  8. import java.security.KeyStore;  
  9.   
  10. import javax.net.ssl.HostnameVerifier;  
  11. import javax.net.ssl.HttpsURLConnection;  
  12. import javax.net.ssl.KeyManagerFactory;  
  13. import javax.net.ssl.SSLContext;  
  14. import javax.net.ssl.TrustManagerFactory;  
  15.   
  16. public class HttpsPost {  
  17.     /** 
  18.      * 获得KeyStore. 
  19.      * @param keyStorePath 
  20.      *            密钥库路径 
  21.      * @param password 
  22.      *            密码 
  23.      * @return 密钥库 
  24.      * @throws Exception 
  25.      */  
  26.     public static KeyStore getKeyStore(String password, String keyStorePath)  
  27.             throws Exception {  
  28.         // 实例化密钥库  
  29.         KeyStore ks = KeyStore.getInstance("JKS");  
  30.         // 获得密钥库文件流  
  31.         FileInputStream is = new FileInputStream(keyStorePath);  
  32.         // 加载密钥库  
  33.         ks.load(is, password.toCharArray());  
  34.         // 关闭密钥库文件流  
  35.         is.close();  
  36.         return ks;  
  37.     }  
  38.   
  39.     /** 
  40.      * 获得SSLSocketFactory. 
  41.      * @param password 
  42.      *            密码 
  43.      * @param keyStorePath 
  44.      *            密钥库路径 
  45.      * @param trustStorePath 
  46.      *            信任库路径 
  47.      * @return SSLSocketFactory 
  48.      * @throws Exception 
  49.      */  
  50.     public static SSLContext getSSLContext(String password,  
  51.             String keyStorePath, String trustStorePath) throws Exception {  
  52.         // 实例化密钥库  
  53.         KeyManagerFactory keyManagerFactory = KeyManagerFactory  
  54.                 .getInstance(KeyManagerFactory.getDefaultAlgorithm());  
  55.         // 获得密钥库  
  56.         KeyStore keyStore = getKeyStore(password, keyStorePath);  
  57.         // 初始化密钥工厂  
  58.         keyManagerFactory.init(keyStore, password.toCharArray());  
  59.   
  60.         // 实例化信任库  
  61.         TrustManagerFactory trustManagerFactory = TrustManagerFactory  
  62.                 .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  63.         // 获得信任库  
  64.         KeyStore trustStore = getKeyStore(password, trustStorePath);  
  65.         // 初始化信任库  
  66.         trustManagerFactory.init(trustStore);  
  67.         // 实例化SSL上下文  
  68.         SSLContext ctx = SSLContext.getInstance("TLS");  
  69.         // 初始化SSL上下文  
  70.         ctx.init(keyManagerFactory.getKeyManagers(),  
  71.                 trustManagerFactory.getTrustManagers(), null);  
  72.         // 获得SSLSocketFactory  
  73.         return ctx;  
  74.     }  
  75.   
  76.     /** 
  77.      * 初始化HttpsURLConnection. 
  78.      * @param password 
  79.      *            密码 
  80.      * @param keyStorePath 
  81.      *            密钥库路径 
  82.      * @param trustStorePath 
  83.      *            信任库路径 
  84.      * @throws Exception 
  85.      */  
  86.     public static void initHttpsURLConnection(String password,  
  87.             String keyStorePath, String trustStorePath) throws Exception {  
  88.         // 声明SSL上下文  
  89.         SSLContext sslContext = null;  
  90.         // 实例化主机名验证接口  
  91.         HostnameVerifier hnv = new MyHostnameVerifier();  
  92.         try {  
  93.             sslContext = getSSLContext(password, keyStorePath, trustStorePath);  
  94.         } catch (GeneralSecurityException e) {  
  95.             e.printStackTrace();  
  96.         }  
  97.         if (sslContext != null) {  
  98.             HttpsURLConnection.setDefaultSSLSocketFactory(sslContext  
  99.                     .getSocketFactory());  
  100.         }  
  101.         HttpsURLConnection.setDefaultHostnameVerifier(hnv);  
  102.     }  
  103.   
  104.     /** 
  105.      * 发送请求. 
  106.      * @param httpsUrl 
  107.      *            请求的地址 
  108.      * @param xmlStr 
  109.      *            请求的数据 
  110.      */  
  111.     public static void post(String httpsUrl, String xmlStr) {  
  112.         HttpsURLConnection urlCon = null;  
  113.         try {  
  114.             urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();  
  115.             urlCon.setDoInput(true);  
  116.             urlCon.setDoOutput(true);  
  117.             urlCon.setRequestMethod("POST");  
  118.             urlCon.setRequestProperty("Content-Length",  
  119.                     String.valueOf(xmlStr.getBytes().length));  
  120.             urlCon.setUseCaches(false);  
  121.             //设置为gbk可以解决服务器接收时读取的数据中文乱码问题  
  122.             urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));  
  123.             urlCon.getOutputStream().flush();  
  124.             urlCon.getOutputStream().close();  
  125.             BufferedReader in = new BufferedReader(new InputStreamReader(  
  126.                     urlCon.getInputStream()));  
  127.             String line;  
  128.             while ((line = in.readLine()) != null) {  
  129.                 System.out.println(line);  
  130.             }  
  131.         } catch (MalformedURLException e) {  
  132.             e.printStackTrace();  
  133.         } catch (IOException e) {  
  134.             e.printStackTrace();  
  135.         } catch (Exception e) {  
  136.             e.printStackTrace();  
  137.         }  
  138.     }  
  139.   
  140.     /** 
  141.      * 测试方法. 
  142.      * @param args 
  143.      * @throws Exception 
  144.      */  
  145.     public static void main(String[] args) throws Exception {  
  146.         // 密码  
  147.         String password = "123456";  
  148.         // 密钥库  
  149.         String keyStorePath = "tomcat.keystore";  
  150.         // 信任库  
  151.         String trustStorePath = "tomcat.keystore";  
  152.         // 本地起的https服务  
  153.         String httpsUrl = "https://localhost:8443/service/httpsPost";  
  154.         // 传输文本  
  155.         String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fruit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";  
  156.         HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);  
  157.         // 发起请求  
  158.         HttpsPost.post(httpsUrl, xmlStr);  
  159.     }  
  160. }  

[java]  view plain copy
  1. import javax.net.ssl.HostnameVerifier;  
  2. import javax.net.ssl.SSLSession;  
  3.   
  4. /** 
  5.  * 实现用于主机名验证的基接口。  
  6.  * 在握手期间,如果 URL 的主机名和服务器的标识主机名不匹配,则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。 
  7.  */  
  8. public class MyHostnameVerifier implements HostnameVerifier {  
  9.     @Override  
  10.     public boolean verify(String hostname, SSLSession session) {  
  11.         if("localhost".equals(hostname)){  
  12.             return true;  
  13.         } else {  
  14.             return false;  
  15.         }  
  16.     }  
  17. }  

接收请求的Web应用:

web.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <servlet>  
  8.     <servlet-name>rollBack</servlet-name>  
  9.     <servlet-class>rollBack</servlet-class>  
  10.   </servlet>  
  11.   
  12.   <servlet-mapping>  
  13.     <servlet-name>rollBack</servlet-name>  
  14.     <url-pattern>/httpsPost</url-pattern>  
  15.   </servlet-mapping>  
  16.   <welcome-file-list>  
  17.     <welcome-file>index.jsp</welcome-file>  
  18.   </welcome-file-list>  
  19. </web-app>  

rollBack servlet

[java]  view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.ServletInputStream;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11.   
  12. public class rollBack extends HttpServlet {  
  13.   
  14.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  15.             throws ServletException, IOException {  
  16.         //获取请求流  
  17.         ServletInputStream sis = request.getInputStream();  
  18.         BufferedReader in = new BufferedReader(new InputStreamReader(sis));  
  19.         String line;  
  20.         if((line = in.readLine()) != null){  
  21.             System.out.println(line);  
  22.         }  
  23.         in.close();  
  24.     }  
  25.   
  26.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  27.             throws ServletException, IOException {  
  28.         this.doGet(request, response);  
  29.     }  
  30. }  

你可能感兴趣的:(Java https请求 HttpsURLConnection)