java 通过 SSL 发送 Post

  1. package server.admin.login;  
  2. import java.io.BufferedReader;  
  3. import java.io.DataOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6.   
  7. import java.net.URL;  
  8. import java.net.URLEncoder;  
  9. import java.security.cert.CertificateException;  
  10. import java.security.cert.CertificateExpiredException;  
  11. import java.security.cert.CertificateNotYetValidException;  
  12. import java.security.cert.X509Certificate;  
  13.   
  14. import javax.net.ssl.HostnameVerifier;  
  15. import javax.net.ssl.HttpsURLConnection;  
  16. import javax.net.ssl.SSLContext;  
  17. import javax.net.ssl.SSLSession;  
  18. import javax.net.ssl.SSLSocketFactory;  
  19. import javax.net.ssl.TrustManager;  
  20. import javax.net.ssl.X509TrustManager;  
  21.   
  22. import org.apache.commons.logging.Log;  
  23. import org.apache.commons.logging.LogFactory;  
  24. import org.apache.log4j.Logger;   
  25.   
  26.   
  27. public class Test {  
  28.       
  29.     public static Logger log=Logger.getLogger("Test.class");  
  30.   
  31.     public static SSLSocketFactory init() throws Exception {  
  32.   
  33.         class MyX509TrustManager implements X509TrustManager {  
  34.               
  35.             public MyX509TrustManager() throws Exception {  
  36.                 // do nothing  
  37.             }  
  38.   
  39.             @Override  
  40.             public void checkClientTrusted(X509Certificate[] chain,  
  41.                     String authType) throws CertificateException {  
  42.                   
  43.             }  
  44.   
  45.             @Override  
  46.             public void checkServerTrusted(X509Certificate[] chain,  
  47.                     String authType) throws CertificateException {  
  48.                   
  49.                 /* 
  50.                 log.info("authType is " + authType);   
  51.                 log.info("cert issuers");   
  52.                  
  53.                 try{ 
  54.                     for (int i = 0; i < chain.length; i++) {   
  55.                         log.info("\t" + chain[i].getIssuerX500Principal().getName());   
  56.                         log.info("\t" + chain[i].getIssuerDN().getName());  
  57.                         chain[i].checkValidity(); 
  58.                     }  
  59.                 }catch(CertificateExpiredException ex){ 
  60.                     log.error("checkDate: Certificate has expired");     
  61.                 }catch(CertificateNotYetValidException yet){ 
  62.                     log.error("checkDate: Certificate is not yet valid"); 
  63.                 }catch(Exception ee){ 
  64.                     log.error("Error: "+ee.getMessage()); 
  65.                 }*/  
  66.   
  67.             }  
  68.   
  69.             @Override  
  70.             public X509Certificate[] getAcceptedIssuers() {  
  71.                 return new X509Certificate[] {};  
  72.             }  
  73.         }  
  74.         TrustManager[] tm = { new MyX509TrustManager() };  
  75.           
  76.         System.setProperty("https.protocols""TLSv1");  
  77.         SSLContext sslContext = SSLContext.getInstance("TLSv1","SunJSSE");  
  78.         sslContext.init(null, tm, new java.security.SecureRandom());  
  79.         SSLSocketFactory ssf = sslContext.getSocketFactory();  
  80.           
  81.         return ssf;  
  82.     }  
  83.       
  84.     /** 
  85.      *  
  86.      * @param POST_URL 
  87.      * @param token 
  88.      * @return 
  89.      * @throws IOException 
  90.      */  
  91.     private static boolean sendHttpsPost(String POST_URL,String token)throws IOException{  
  92.           
  93.         boolean returnVal=false;  
  94.            
  95.         URL myURL = new URL(POST_URL);  
  96.           
  97.         HttpsURLConnection con = (HttpsURLConnection) myURL.openConnection();  
  98.           
  99.         HostnameVerifier hostNameVerify = new HostnameVerifier()  
  100.         {  
  101.             /** 
  102.              * Always return true 
  103.              */  
  104.             public boolean verify(String urlHostName, SSLSession session)  
  105.             {  
  106.                 return true;  
  107.             }  
  108.         };  
  109.         //HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerify);  
  110.         con.setHostnameVerifier(hostNameVerify);  
  111.         try {  
  112.             con.setSSLSocketFactory(init());  
  113.         } catch (Exception e1) {  
  114.             // throw out the exception  
  115.             throw new IOException(e1);  
  116.         }  
  117.           
  118.         con.setDoOutput(true);      
  119.         con.setDoInput(true);      
  120.         con.setRequestMethod("POST");      
  121.         con.setUseCaches(false);      
  122.         con.setInstanceFollowRedirects(true);      
  123.         con.setRequestProperty("Content-Type "," application/x-www-form-urlencoded ");      
  124.   
  125.         con.connect();   
  126.           
  127.         DataOutputStream out = new DataOutputStream(con.getOutputStream());      
  128.   
  129.         String content = "authenticityToken="+ URLEncoder.encode(token, "utf-8");      
  130.           
  131.         out.writeBytes(content);      
  132.   
  133.         out.flush();      
  134.         out.close();   
  135.       
  136.         BufferedReader reader = new BufferedReader(new InputStreamReader(      
  137.         con.getInputStream()));      
  138.         String line;      
  139.                   
  140.         while ((line = reader.readLine()) != null) {      
  141.               
  142.             if(line.equalsIgnoreCase("ok"))  
  143.                 returnVal=true;  
  144.             else  
  145.                 returnVal=false;  
  146.         }      
  147.         reader.close();      
  148.         con.disconnect();  
  149.       
  150.           
  151.         return returnVal;  
  152.     }  
  153.     public static boolean readContentFromPost(String POST_URL,String token) throws IOException {      
  154.            
  155.             TestLogger.setLog4jLogger(log);  
  156.               
  157.             POST_URL=POST_URL+"validate";  
  158.               
  159.             return sendHttpsPost(POST_URL,token);  
  160.     }  
  161.   
  162.       
  163.   
  164.   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值