HTTPS 客户端发送请求(二)

来源:互联网 发布:自学java不学c语言 编辑:程序博客网 时间:2024/06/05 23:06

https 完整web开发

Tomcat 6.0 配置

1、生成安全访问的证书。

命令行下执行:keytool -genkey -alias tomcat -keyalg RSA -keystore c:\tomcat.keystore

然后按提示输入一些密码等信息:

输入keystore密码:
再次输入新密码:
您的名字与姓氏是什么?
   [Unknown]:  tomcat
您的组织单位名称是什么?
   [Unknown]:  tomcat

您的组织名称是什么?
   [Unknown]:  tomcat
您所在的城市或区域名称是什么?
   [Unknown]:  bj
您所在的州或省份名称是什么?
   [Unknown]:  bj
该单位的两字母国家代码是什么
   [Unknown]:  cn
CN=tomcat, OU=tomcat, O=tomcat, L=bj, ST=bj, C=cn 正确吗?
   [否]:  y

输入<tomcat>的主密码
         (如果和 keystore 密码相同,按回车):



输入完成后,会在C盘下生成tomcat.keystore文件,这个文件的位置不做要求。

注:上述命令中的蓝色部分可以不输入,这样会默认生成一个.keystore的证书文件。

2、配置tomcat,使其支持https连接。

打开tomcat目录下conf/server.xml文件,将之前的连接部分注释,找到以下节点:


 

[html] view plaincopy
  1. <!-- Define a SSL HTTP/1.1 Connector on port 8443  
  2.           This connector uses the JSSE configuration, when using APR, the   
  3.          connector should be using the OpenSSL style configuration  
  4.           described in the APR documentation -->  
  5.      <!--  
  6.      <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"  
  7.                 maxThreads="150" scheme="https" secure="true"  
  8.                 clientAuth="false" sslProtocol="TLS" />  
  9.      -->  


 
将<connectore节点的注释去掉,8443修改为你要使用的端口。节点中添加两个属性:keystoreFile="C:/tomcat.keystore" keystorePass="123456"

其中,keystoreFile指的是你第一步生成的证书文件位置,keystorePass是你在生成证书时所输入的密码。
 
通过以上两步操作,基本上就可以使用https访问tomcat连接了,不过我在使用tomcat6配置的时候,启动tomcat报错:


 

[html] view plaincopy
  1. 2011-9-8 10:11:20 org.apache.catalina.core.AprLifecycleListener init  
  2.  信息: Loaded APR based Apache Tomcat Native library 1.1.20.  
  3.  2011-9-8 10:11:20 org.apache.catalina.core.AprLifecycleListener init  
  4.  信息: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].  
  5.  2011-9-8 10:11:20 org.apache.catalina.startup.SetAllPropertiesRule begin  
  6.  警告: [SetAllPropertiesRule]{Server/Service/Connector} Setting property 'keystoreFile' to 'C:\tomcat.keystore' did not find a matching property.  
  7.  2011-9-8 10:11:20 org.apache.catalina.startup.SetAllPropertiesRule begin  
  8.  警告: [SetAllPropertiesRule]{Server/Service/Connector} Setting property 'keystorePass' to 'mvtech' did not find a matching property.  
  9.  2011-9-8 10:11:20 org.apache.catalina.startup.SetAllPropertiesRule begin  
  10.  警告: [SetAllPropertiesRule]{Server/Service/Connector} Setting property 'clientAuth' to 'false' did not find a matching property.  
  11.  2011-9-8 10:11:20 org.apache.coyote.http11.Http11AprProtocol init  
  12.  严重: Error initializing endpoint  
  13.  java.lang.Exception: No Certificate file specified or invalid file format  
  14.   at org.apache.tomcat.jni.SSLContext.setCertificate(Native Method)  
  15.   at org.apache.tomcat.util.net.AprEndpoint.init(AprEndpoint.java:720)  
  16.   at org.apache.coyote.http11.Http11AprProtocol.init(Http11AprProtocol.java:107)  
  17.   at org.apache.catalina.connector.Connector.initialize(Connector.java:1014)  
  18.   at org.apache.catalina.core.StandardService.initialize(StandardService.java:680)  
  19.   at org.apache.catalina.core.StandardServer.initialize(StandardServer.java:795)  
  20.   at org.apache.catalina.startup.Catalina.load(Catalina.java:524)  
  21.   at org.apache.catalina.startup.Catalina.load(Catalina.java:548)  
  22.   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
  23.   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)  
  24.   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)  
  25.   at java.lang.reflect.Method.invoke(Method.java:597)  
  26.   at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)  
  27.   at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)  
  28.  2011-9-8 10:11:20 org.apache.catalina.startup.Catalina load  
  29.  严重: Catalina.start  
  30.  LifecycleException:  Protocol handler initialization failed: java.lang.Exception: No Certificate file specified or invalid file format  
  31.   at org.apache.catalina.connector.Connector.initialize(Connector.java:1016)  
  32.   at org.apache.catalina.core.StandardService.initialize(StandardService.java:680)  
  33.   at org.apache.catalina.core.StandardServer.initialize(StandardServer.java:795)  
  34.   at org.apache.catalina.startup.Catalina.load(Catalina.java:524)  
  35.   at org.apache.catalina.startup.Catalina.load(Catalina.java:548)  
  36.   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
  37.   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)  
  38.   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)  
  39.   at java.lang.reflect.Method.invoke(Method.java:597)  
  40.   at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)  
  41.   at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)  


在网上看到有朋友的解决办法,是找到tomcat的bin目录下有个tcnative-1.dll文件,然后将其删除,重新启动tomcat一切正常。

至此,可以通过https方式访问你的应用了。

但是此时如果你用Http方式访问应用,页面会返回乱码或者空,但是也不报错,为了更好的使用,我们需要在客户输入http时能够自动跳转到Https方式,这就需要第三步,让你的应用强制使用https方式访问了。
 
打开tomcat下conf/web.xml文件,在最下方的<welcome-file-list>节点之后添加:

[html] view plaincopy
  1. <login-config>     
  2.     <!-- Authorization setting for SSL -->     
  3.     <auth-method>CLIENT-CERT</auth-method>     
  4.     <realm-name>Client Cert Users-only Area</realm-name>     
  5.     </login-config>     
  6.     <security-constraint>     
  7.         <!-- Authorization setting for SSL -->     
  8.         <web-resource-collection >     
  9.             <web-resource-name >SSL</web-resource-name>     
  10.             <url-pattern>/*</url-pattern>     
  11.         </web-resource-collection>     
  12.         <user-data-constraint>     
  13.             <transport-guarantee>CONFIDENTIAL</transport-guarantee>     
  14.         </user-data-constraint>     
  15.     </security-constraint>     

 

配置完成。。。。。。

源码解析

服务端

服务端的构建比较简单,一个action搞定

 

[html] view plaincopy
  1. package com.httpsDemo.action;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. public class PostHttpsAction extends HttpServlet {  
  14.   
  15.     /**  
  16.      *   
  17.      */  
  18.     private static final long serialVersionUID = 1L;  
  19.   
  20.     @Override  
  21.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  22.             throws ServletException, IOException {  
  23.         System.out.println("post success ...");  
  24.         InputStream in = req.getInputStream();  
  25.         BufferedReader br = new BufferedReader(new InputStreamReader(in));  
  26.         String result = br.readLine();  
  27.         System.out.println(result);  
  28.         resp.getOutputStream().write(result.getBytes("utf-8"));  
  29.         return;  
  30.     }  
  31.   
  32. }  

 

注意web.xml配置.

客户端

工具类一个搞定

 

[html] view plaincopy
  1. package com.saygou.weixin;  
  2.    
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.DataOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.net.URL;  
  8. import java.security.KeyManagementException;  
  9. import java.security.NoSuchAlgorithmException;  
  10. import java.security.cert.CertificateException;  
  11. import java.security.cert.X509Certificate;  
  12.    
  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.TrustManager;  
  19. import javax.net.ssl.X509TrustManager;  
  20.    
  21. public class HttpsUtil {  
  22.    
  23.     private static class TrustAnyTrustManager implements X509TrustManager {  
  24.    
  25.         public void checkClientTrusted(X509Certificate[] chain, String authType)  
  26.                 throws CertificateException {  
  27.         }  
  28.    
  29.         public void checkServerTrusted(X509Certificate[] chain, String authType)  
  30.                 throws CertificateException {  
  31.         }  
  32.    
  33.         public X509Certificate[] getAcceptedIssuers() {  
  34.             return new X509Certificate[] {};  
  35.         }  
  36.     }  
  37.    
  38.     private static class TrustAnyHostnameVerifier implements HostnameVerifier {  
  39.         public boolean verify(String hostname, SSLSession session) {  
  40.             return true;  
  41.         }  
  42.     }  
  43.    
  44.     /**  
  45.      * post方式请求服务器(https协议)  
  46.      *   
  47.      * @param url  
  48.      *            请求地址  
  49.      * @param content  
  50.      *            参数  
  51.      * @param charset  
  52.      *            编码  
  53.      * @return  
  54.      * @throws NoSuchAlgorithmException  
  55.      * @throws KeyManagementException  
  56.      * @throws IOException  
  57.      */  
  58.     public static byte[] post(String url, String content, String charset)  
  59.             throws NoSuchAlgorithmException, Exception,  
  60.             IOException {  
  61.         SSLContext sc = SSLContext.getInstance("SSL","SunJSSE");  
  62.         sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },  
  63.                 new java.security.SecureRandom());  
  64.    
  65.         URL console = new URL(url);  
  66.         HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();  
  67.         conn.setSSLSocketFactory(sc.getSocketFactory());  
  68.         //设置默认证书--如果没有这句将会报错,错误信息↓↓↓  
  69.         //java.io.IOException: HTTPS hostname wrong:  should be <127.0.0.1>   
  70.         conn.setHostnameVerifier(new TrustAnyHostnameVerifier());  
  71.         conn.setDoOutput(true);  
  72.         conn.connect();  
  73.         DataOutputStream out = new DataOutputStream(conn.getOutputStream());  
  74.         out.write(content.getBytes(charset));  
  75.         // 刷新、关闭  
  76.         out.flush();  
  77.         out.close();  
  78.         InputStream is = conn.getInputStream();  
  79.         if (is != null) {  
  80.             ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  81.             byte[] buffer = new byte[1024];  
  82.             int len = 0;  
  83.             while ((len = is.read(buffer)) != -1) {  
  84.                 outStream.write(buffer, 0, len);  
  85.             }  
  86.             is.close();  
  87.             return outStream.toByteArray();  
  88.         }  
  89.         return null;  
  90.     }  
  91.       
  92.    /**  
  93.     * 测试  
  94.     * @param args  
  95.     * @throws Exception  
  96.     */  
  97.    
  98.     public static void main(String[] args) throws Exception {  
  99.         try {  
  100.             byte[] b = HttpsUtil.post("https://127.0.0.1:8443/httpsDemo/hs", "{'name':'Jack'}", "utf-8");  
  101.             System.out.println(new String(b));  
  102.         } catch (KeyManagementException e) {  
  103.             // TODO Auto-generated catch block  
  104.             e.printStackTrace();  
  105.         } catch (NoSuchAlgorithmException e) {  
  106.             // TODO Auto-generated catch block  
  107.             e.printStackTrace();  
  108.         } catch (IOException e) {  
  109.             // TODO Auto-generated catch block  
  110.             e.printStackTrace();  
  111.         }  
  112.     }  
  113. }  
0 0
原创粉丝点击