天天看点

Java 发送https 的post请求方法

  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. import javax.net.ssl.HostnameVerifier;  
  10. import javax.net.ssl.HttpsURLConnection;  
  11. import javax.net.ssl.KeyManagerFactory;  
  12. import javax.net.ssl.SSLContext;  
  13. import javax.net.ssl.TrustManagerFactory;  
  14. public class HttpsPost {  
  15.     public static KeyStore getKeyStore(String password, String keyStorePath)  
  16.             throws Exception {  
  17.         // 实例化密钥库  
  18.         KeyStore ks = KeyStore.getInstance("JKS");  
  19.         // 获得密钥库文件流  
  20.         FileInputStream is = new FileInputStream(keyStorePath);  
  21.         // 加载密钥库  
  22.         ks.load(is, password.toCharArray());  
  23.         // 关闭密钥库文件流  
  24.         is.close();  
  25.         return ks;  
  26.     }  
  27.     public static SSLContext getSSLContext(String password,  
  28.             String keyStorePath, String trustStorePath) throws Exception {  
  29.         // 实例化密钥库  
  30.         KeyManagerFactory keyManagerFactory = KeyManagerFactory  
  31.                 .getInstance(KeyManagerFactory.getDefaultAlgorithm());  
  32.         // 获得密钥库  
  33.         KeyStore keyStore = getKeyStore(password, keyStorePath);  
  34.         // 初始化密钥工厂  
  35.         keyManagerFactory.init(keyStore, password.toCharArray());  
  36.         // 实例化信任库  
  37.         TrustManagerFactory trustManagerFactory = TrustManagerFactory  
  38.                 .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  39.         // 获得信任库  
  40.         KeyStore trustStore = getKeyStore(password, trustStorePath);  
  41.         // 初始化信任库  
  42.         trustManagerFactory.init(trustStore);  
  43.         // 实例化SSL上下文  
  44.         SSLContext ctx = SSLContext.getInstance("TLS");  
  45.         // 初始化SSL上下文  
  46.         ctx.init(keyManagerFactory.getKeyManagers(),  
  47.                 trustManagerFactory.getTrustManagers(), null);  
  48.         // 获得SSLSocketFactory  
  49.         return ctx;  
  50.     }  
  51.     public static void initHttpsURLConnection(String password,  
  52.             String keyStorePath, String trustStorePath) throws Exception {  
  53.         // 声明SSL上下文  
  54.         SSLContext sslContext = null;  
  55.         // 实例化主机名验证接口  
  56.         HostnameVerifier hnv = new MyHostnameVerifier();  
  57.         try {  
  58.             sslContext = getSSLContext(password, keyStorePath, trustStorePath);  
  59.         } catch (GeneralSecurityException e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.         if (sslContext != null) {  
  63.             HttpsURLConnection.setDefaultSSLSocketFactory(sslContext  
  64.                     .getSocketFactory());  
  65.         }  
  66.         HttpsURLConnection.setDefaultHostnameVerifier(hnv);  
  67.     }  
  68.     public static void post(String httpsUrl, String xmlStr) {  
  69.         HttpsURLConnection urlCon = null;  
  70.         try {  
  71.             urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();  
  72.             urlCon.setDoInput(true);  
  73.             urlCon.setDoOutput(true);  
  74.             urlCon.setRequestMethod("POST");  
  75.             urlCon.setRequestProperty("Content-Length",  
  76.                     String.valueOf(xmlStr.getBytes().length));  
  77.             urlCon.setUseCaches(false);  
  78.             //设置为gbk可以解决服务器接收时读取的数据中文乱码问题  
  79.             urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));  
  80.             urlCon.getOutputStream().flush();  
  81.             urlCon.getOutputStream().close();  
  82.             BufferedReader in = new BufferedReader(new InputStreamReader(  
  83.                     urlCon.getInputStream()));  
  84.             String line;  
  85.             while ((line = in.readLine()) != null) {  
  86.                 System.out.println(line);  
  87.             }  
  88.         } catch (MalformedURLException e) {  
  89.             e.printStackTrace();  
  90.         } catch (IOException e) {  
  91.             e.printStackTrace();  
  92.         } catch (Exception e) {  
  93.             e.printStackTrace();  
  94.         }  
  95.     }  
  96.     public static void main(String[] args) throws Exception {  
  97.         // 密码  
  98.         String password = "123456";  
  99.         // 密钥库  
  100.         String keyStorePath = "tomcat.keystore";  
  101.         // 信任库  
  102.         String trustStorePath = "tomcat.keystore";  
  103.         // 本地起的https服务  
  104.         String httpsUrl = "https://localhost:8443/service/httpsPost";  
  105.         // 传输文本  
  106.         String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fruit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";  
  107.         HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);  
  108.         // 发起请求  
  109.         HttpsPost.post(httpsUrl, xmlStr);  
  110.     }  
  111. }  

[java]  view plain copy

  1. import javax.net.ssl.HostnameVerifier;  
  2. import javax.net.ssl.SSLSession;  
  3. public class MyHostnameVerifier implements HostnameVerifier {  
  4.     @Override  
  5.     public boolean verify(String hostname, SSLSession session) {  
  6.         if("localhost".equals(hostname)){  
  7.             return true;  
  8.         } else {  
  9.             return false;  
  10.         }  
  11.     }  
  12. }  

接收请求的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.   <servlet-mapping>  
  12.     <servlet-name>rollBack</servlet-name>  
  13.     <url-pattern>/httpsPost</url-pattern>  
  14.   </servlet-mapping>  
  15.   <welcome-file-list>  
  16.     <welcome-file>index.jsp</welcome-file>  
  17.   </welcome-file-list>  
  18. </web-app>  

rollBack servlet

[java]  view plain copy

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