JAVA调用HTTPS双向认证API

本文提供了一个Java类示例,展示了如何使用HTTPS进行GET和POST请求,并详细介绍了如何配置SSL上下文来确保通信的安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[java]  view plain  copy
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.io.PrintWriter;  
  8. import java.io.UnsupportedEncodingException;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11. import java.security.KeyManagementException;  
  12. import java.security.KeyStore;  
  13. import java.security.KeyStoreException;  
  14. import java.security.NoSuchAlgorithmException;  
  15. import java.security.SecureRandom;  
  16. import java.security.UnrecoverableKeyException;  
  17. import java.security.cert.CertificateException;  
  18. import java.util.List;  
  19. import java.util.Map;  
  20.   
  21. import javax.net.ssl.HostnameVerifier;  
  22. import javax.net.ssl.HttpsURLConnection;  
  23. import javax.net.ssl.KeyManager;  
  24. import javax.net.ssl.KeyManagerFactory;  
  25. import javax.net.ssl.SSLContext;  
  26. import javax.net.ssl.SSLSession;  
  27. import javax.net.ssl.TrustManager;  
  28. import javax.net.ssl.TrustManagerFactory;  
  29.   
  30.   
  31. public class HttpTest {  
  32.     public static String KEY_STORE_FILE="imp_client.p12";  
  33.     public static String KEY_STORE_PASS="nymeria";  
  34.     public static String TRUST_STORE_FILE="cvte.com.jks";  
  35.     public static String TRUST_STORE_PASS="123456";  
  36.   
  37.   
  38.     private static SSLContext sslContext;  
  39.     /** 
  40.      * 向指定URL发送GET方法的请求 
  41.      *  
  42.      * @param url 
  43.      *            发送请求的URL 
  44.      * @param param 
  45.      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 
  46.      * @return URL 所代表远程资源的响应结果 
  47.      *  
  48.      */  
  49.     public static String sendGet(String url, String param) {  
  50.         String result = "";  
  51.         BufferedReader in = null;  
  52.         try {  
  53.             String urlNameString = url + "?" + param;  
  54.             URL realUrl = new URL(urlNameString);  
  55.             // 打开和URL之间的连接  
  56.             HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();  
  57.             // 打开和URL之间的连接  
  58.             if(connection instanceof HttpsURLConnection){  
  59.                 ((HttpsURLConnection)connection)  
  60.                 .setSSLSocketFactory(getSSLContext().getSocketFactory());  
  61.             }  
  62.   
  63.             // 设置通用的请求属性  
  64.             connection.setRequestProperty("accept""*/*");  
  65.             connection.setRequestProperty("connection""Keep-Alive");  
  66.             connection.setRequestProperty("user-agent",  
  67.                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
  68.             // 建立实际的连接  
  69.             connection.connect();  
  70.             // 获取所有响应头字段  
  71.             Map<String, List<String>> map = connection.getHeaderFields();  
  72.             // 遍历所有的响应头字段  
  73.             for (String key : map.keySet()) {  
  74.                 //System.out.println(key + "--->" + map.get(key));  
  75.             }  
  76.             // 定义 BufferedReader输入流来读取URL的响应  
  77.   
  78.             if(connection.getResponseCode()==200){  
  79.                 in = new BufferedReader(new InputStreamReader(  
  80.                         connection.getInputStream()));  
  81.             }else{  
  82.                 in = new BufferedReader(new InputStreamReader(  
  83.                         connection.getErrorStream()));  
  84.             }  
  85.             String line;  
  86.             while ((line = in.readLine()) != null) {  
  87.                 result += line;  
  88.             }  
  89.   
  90.         } catch (Exception e) {  
  91.             System.out.println("发送GET请求出现异常!" + e);  
  92.             e.printStackTrace();  
  93.         }  
  94.         // 使用finally块来关闭输入流  
  95.         finally {  
  96.             try {  
  97.                 if (in != null) {  
  98.                     in.close();  
  99.                 }  
  100.             } catch (Exception e2) {  
  101.                 e2.printStackTrace();  
  102.             }  
  103.         }  
  104.         return result;  
  105.     }  
  106.   
  107.     /**  
  108.      * 向指定 URL 发送POST方法的请求  
  109.      *   
  110.      * @param url  
  111.      *            发送请求的 URL  
  112.      * @param param  
  113.      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
  114.      * @return 所代表远程资源的响应结果  
  115.      */  
  116.     public static String sendPost(String url, String param) {  
  117.         PrintWriter out = null;  
  118.         BufferedReader in = null;  
  119.         String result = "";  
  120.         try {  
  121.             URL realUrl = new URL(url);  
  122.             // 打开和URL之间的连接  
  123.             HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();  
  124.             if(conn instanceof HttpsURLConnection){  
  125.                 ((HttpsURLConnection)conn)  
  126.                 .setSSLSocketFactory(getSSLContext().getSocketFactory());  
  127.             }  
  128.             // 设置通用的请求属性  
  129.             conn.setRequestProperty("accept""*/*");  
  130.             conn.setRequestProperty("connection""Keep-Alive");  
  131.             conn.setRequestProperty("user-agent",  
  132.                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
  133.             // 发送POST请求必须设置如下两行  
  134.             conn.setDoOutput(true);  
  135.             conn.setDoInput(true);  
  136.             // 获取URLConnection对象对应的输出流  
  137.             out = new PrintWriter(conn.getOutputStream());  
  138.             // 发送请求参数  
  139.             out.print(param);  
  140.             // flush输出流的缓冲  
  141.             out.flush();  
  142.             // 定义BufferedReader输入流来读取URL的响应  
  143.             if(conn.getResponseCode()==200){  
  144.                 in = new BufferedReader(  
  145.                         new InputStreamReader(conn.getInputStream()));  
  146.             }else{  
  147.                 in = new BufferedReader(  
  148.                         new InputStreamReader(conn.getErrorStream()));  
  149.             }  
  150.             String line="";  
  151.             while ((line = in.readLine()) != null) {  
  152.                 result += line;  
  153.             }  
  154.         } catch (Exception e) {  
  155.             System.out.println("发送 POST 请求出现异常!"+e);  
  156.             e.printStackTrace();  
  157.         }  
  158.         //使用finally块来关闭输出流、输入流  
  159.         finally{  
  160.             try{  
  161.                 if(out!=null){  
  162.                     out.close();  
  163.                 }  
  164.                 if(in!=null){  
  165.                     in.close();  
  166.                 }  
  167.             }catch(IOException ex){  
  168.                 ex.printStackTrace();  
  169.             }  
  170.         }  
  171.         return result;  
  172.     }      
  173.   
  174.     public static SSLContext getSSLContext(){  
  175.         long time1=System.currentTimeMillis();  
  176.         if(sslContext==null){  
  177.             try {  
  178.                 KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");  
  179.                 kmf.init(getkeyStore(),KEY_STORE_PASS.toCharArray());  
  180.                 KeyManager[] keyManagers = kmf.getKeyManagers();  
  181.   
  182.                 TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance("SunX509");  
  183.                 trustManagerFactory.init(getTrustStore());  
  184.                 TrustManager[]  trustManagers= trustManagerFactory.getTrustManagers();  
  185.   
  186.                 sslContext = SSLContext.getInstance("TLS");  
  187.                 sslContext.init(keyManagers, trustManagers, new SecureRandom());  
  188.                 HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {  
  189.                     @Override  
  190.                     public boolean verify(String hostname, SSLSession session) {  
  191.                         return true;  
  192.                     }  
  193.                 });  
  194.             } catch (FileNotFoundException e) {  
  195.                 e.printStackTrace();  
  196.             } catch (NoSuchAlgorithmException e) {  
  197.                 e.printStackTrace();  
  198.             } catch (IOException e) {  
  199.                 e.printStackTrace();  
  200.             } catch (UnrecoverableKeyException e) {  
  201.                 e.printStackTrace();  
  202.             } catch (KeyStoreException e) {  
  203.                 e.printStackTrace();  
  204.             } catch (KeyManagementException e) {  
  205.                 e.printStackTrace();  
  206.             }  
  207.         }  
  208.         long time2=System.currentTimeMillis();  
  209.         System.out.println("SSLContext 初始化时间:"+(time2-time1));  
  210.         return sslContext;  
  211.     }  
  212.   
  213.   
  214.     public static KeyStore getkeyStore(){  
  215.         KeyStore keySotre=null;  
  216.         try {  
  217.             keySotre = KeyStore.getInstance("PKCS12");  
  218.             FileInputStream fis = new FileInputStream(new File(KEY_STORE_FILE));  
  219.             keySotre.load(fis, KEY_STORE_PASS.toCharArray());  
  220.             fis.close();  
  221.         } catch (KeyStoreException e) {  
  222.             e.printStackTrace();  
  223.         } catch (FileNotFoundException e) {  
  224.             e.printStackTrace();  
  225.         } catch (NoSuchAlgorithmException e) {  
  226.             e.printStackTrace();  
  227.         } catch (CertificateException e) {  
  228.             e.printStackTrace();  
  229.         } catch (IOException e) {  
  230.             e.printStackTrace();  
  231.         }  
  232.         return keySotre;  
  233.     }  
  234.     public static KeyStore getTrustStore() throws IOException{  
  235.         KeyStore trustKeyStore=null;  
  236.         FileInputStream fis=null;  
  237.         try {  
  238.             trustKeyStore=KeyStore.getInstance("JKS");  
  239.             fis = new FileInputStream(new File(TRUST_STORE_FILE));  
  240.             trustKeyStore.load(fis, TRUST_STORE_PASS.toCharArray());  
  241.         } catch (FileNotFoundException e) {  
  242.             e.printStackTrace();  
  243.         } catch (KeyStoreException e) {  
  244.             e.printStackTrace();  
  245.         } catch (NoSuchAlgorithmException e) {  
  246.             e.printStackTrace();  
  247.         } catch (CertificateException e) {  
  248.             e.printStackTrace();  
  249.         } catch (IOException e) {  
  250.             e.printStackTrace();  
  251.         }finally{  
  252.             fis.close();  
  253.         }  
  254.         return trustKeyStore;  
  255.     }  
  256.     public static void main(String[] args) throws UnsupportedEncodingException {  
  257.         Long time1=System.currentTimeMillis();  
  258.         int k=0;  
  259.         for(int i=0;i<100;++i){  
  260.             String result=sendGet("https://test.com""username=x1");  
  261.             System.out.println(result);  
  262.             ++k;  
  263.         }  
  264.         Long time2=System.currentTimeMillis();  
  265.         System.out.println("平均耗费时间:"+(time2-time1)/k);  
  266.     }  
  267. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值