使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL

这里使用的是HttpComponents-Client-4.1.2

  1 package com.jadyer.util;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.IOException;
  7 import java.security.KeyManagementException;
  8 import java.security.KeyStore;
  9 import java.security.KeyStoreException;
 10 import java.security.NoSuchAlgorithmException;
 11 import java.security.UnrecoverableKeyException;
 12 import java.security.cert.CertificateException;
 13 
 14 import org.apache.http.HttpEntity;
 15 import org.apache.http.HttpResponse;
 16 import org.apache.http.ParseException;
 17 import org.apache.http.client.ClientProtocolException;
 18 import org.apache.http.client.HttpClient;
 19 import org.apache.http.client.methods.HttpGet;
 20 import org.apache.http.conn.scheme.Scheme;
 21 import org.apache.http.conn.ssl.SSLSocketFactory;
 22 import org.apache.http.impl.client.DefaultHttpClient;
 23 import org.apache.http.util.EntityUtils;
 24 
 25 /**
 26  * 使用HttpClient模拟HTTPS访问
 27  * @see ===================================================================================================================================
 28  * @see 【配置Tomcat支持SSL(即让Tomcat下的Web应用处于SSL安全通道中)】
 29  * @see ===================================================================================================================================
 30  * @see 1、生成KeyStore
 31  * @see    1)运行-->CMD-->"keytool -genkey -alias Jadyer_SSL_20120508 -keyalg RSA -validity 1024 -keystore D:\Jadyer_SSL_20120508.keystore"
 32  * @see      参数说明----->-genkey  表示生成密钥
 33  * @see                   -alias    指定别名,这里是Jadyer_SSL_20120508
 34  * @see                   -keyalg   指定算法,这里是RSA
 35  * @see                   -validity 指定证书有效期,这里是1024天
 36  * @see                   -keystore 指定存储位置,这里是D:\\Jadyer_SSL_20120508.keystore
 37  * @see    2)CMD输出----->输入keystore密码:hongyu75
 38  * @see                   再次输入新密码:hongyu75
 39  * @see                   您的名字与姓氏是什么?[Unknown]:127.0.0.1(这里要根据实际情况填写网站域名或者IP,否则会出现证书上的名称无效)
 40  * @see                   您的组织单位名称是什么?[Unknown]:http://blog.csdn.net/jadyer
 41  * @see                   您的组织名称是什么?[Unknown]:JavaLover_jadyer
 42  * @see                   您所在的城市或区域名称是什么?[Unknown]:BJ
 43  * @see                   您所在的州或省份名称是什么?[Unknown]:BJ_NanTian
 44  * @see                   该单位的两字母国家代码是什么[Unknown]:CN
 45  * @see                   CN=127.0.0.1, OU=http://blog.csdn.net/jadyer, O=JavaLover_jadyer, L=BJ, ST=BJ_NanTian, C=CN 正确吗?[否]:Y
 46  * @see                   输入<Jadyer_SSL_20120508>的主密码(如果和 keystore 密码相同,按回车):这里按回车键
 47  * @see                   (这里的主密码一定要与keystore密码相同,否则启动Tomcat时就会告诉你java.io.IOException: Cannot recover key)
 48  * @see    3)接下来就会按照-keystore参数值在指定位置生成指定的KeyStore文件了
 49  * @see ===================================================================================================================================
 50  * @see 2、让Tomcat支持SSL
 51  * @see    1)将生成的Jadyer_SSL_20120508.keystore拷贝到\\%TOMCAT_HOME%\\conf\\目录中(其它目录也可以)
 52  * @see    2)修改\\%TOMCAT_HOME%\\conf\\server.xml文件(大约在85行的位置),新增内容如下
 53  * @see      <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
 54  * @see                 maxThreads="150" scheme="https" secure="true"
 55  * @see                 clientAuth="false" sslProtocol="TLS" URIEncoding="UTF-8"
 56  * @see                 keystoreFile="conf/Jadyer_SSL_20120508.keystore" keystorePass="hongyu75"/>
 57  * @see    3)这样,我们的Tomcat就支持HTTPS访问了(关于<Connector/>标签中的属性说明,参拜Google大神)
 58  * @see ===================================================================================================================================
 59  * @see 3、用浏览器访问我们的应用
 60  * @see   1)输入https://127.0.0.1:8443/blog会发现你的应用已经处于SSL安全通道中了
 61  * @see     此时,如果我们在浏览器里访问http://127.0.0.1:8443/blog会发现,竟然能访问
 62  * @see     也就是说,我们虽然启用了HTTPS,但现在还可以绕开HTTPS直接访问HTTP还能,这样HTTPS也就起不到作用了
 63  * @see   2)我们可以配置一下\\%TOMCAT_HOME%\\conf\\web.xml文件,使得HTTP的访问能够重定向到HTTPS的连接
 64  * @see     修改位置大约为web.xml的1224行,即在</welcome-file-list>标签后面加入下面的内容,即可
 65  * @see     <security-constraint>
 66  * @see         <!-- Authorization setting for SSL -->
 67  * @see         <web-resource-collection>
 68  * @see             <web-resource-name>SSL_App</web-resource-name>
 69  * @see             <!-- 指明需要SSL的url -->
 70  * @see             <url-pattern>/*</url-pattern>
 71  * @see             <http-method>GET</http-method>
 72  * @see             <http-method>POST</http-method>
 73  * @see         </web-resource-collection>
 74  * @see         <user-data-constraint>
 75  * @see             <!-- 指明需要SSL -->
 76  * @see             <transport-guarantee>CONFIDENTIAL</transport-guarantee>
 77  * @see         </user-data-constraint>
 78  * @see     </security-constraint>
 79  * @see ===================================================================================================================================
 80  * @author http://blog.csdn.net/jadyer
 81  * @editor Feb 1, 2012 3:02:27 PM
 82  */
 83 public class HttpClientUtil {
 84     public static void main(String[] args)throws Exception{
 85         //String requestUrl = "http://127.0.0.1:8088/test/web/userac";
 86         String requestUrl = "https://127.0.0.1:8443/test/web/userac";
 87         System.out.println(sendSSLRequest(requestUrl));
 88     }
 89     
 90     /**
 91      * 发送HTTPS请求
 92      * @param requestUrl 请求的地址
 93      * @return 响应内容
 94      */
 95     @SuppressWarnings("finally")
 96     public static String sendSSLRequest(String requestUrl){
 97         long responseLength = 0;       //响应长度
 98         String responseContent = null; //响应内容
 99         HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
100         try {
101             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
102             FileInputStream fis = new FileInputStream(new File("F:\\Tool\\IDE\\Jadyer_SSL_20120508.keystore"));
103             try {
104                 trustStore.load(fis, "hongyu75".toCharArray()); //加载KeyStore
105             } catch (NoSuchAlgorithmException e) {
106                 e.printStackTrace();
107             } catch (CertificateException e) {
108                 e.printStackTrace();
109             } catch (IOException e) {
110                 e.printStackTrace();
111             } finally {
112                 try {
113                     fis.close();
114                 } catch (IOException e) {
115                     e.printStackTrace();
116                 }
117             }
118             SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);   //创建Socket工厂,将trustStore注入
119             Scheme sch = new Scheme("https", 8443, socketFactory);               //创建Scheme
120             httpClient.getConnectionManager().getSchemeRegistry().register(sch); //注册Scheme
121             HttpGet httpGet = new HttpGet(requestUrl);           //创建HttpGet
122             HttpResponse response = httpClient.execute(httpGet); //执行GET请求
123             HttpEntity entity = response.getEntity();            //获取响应实体
124             if (null != entity) {
125                 responseLength = entity.getContentLength();
126                 responseContent = EntityUtils.toString(entity, "UTF-8");
127                 EntityUtils.consume(entity); //Consume response content
128             }
129             System.out.println("请求地址: " + httpGet.getURI());
130             System.out.println("响应状态: " + response.getStatusLine());
131             System.out.println("响应长度: " + responseLength);
132             System.out.println("响应内容: " + responseContent);
133         } catch (KeyManagementException e) {
134             e.printStackTrace();
135         } catch (UnrecoverableKeyException e) {
136             e.printStackTrace();
137         } catch (KeyStoreException e) {
138             e.printStackTrace();
139         } catch (FileNotFoundException e) {
140             e.printStackTrace();
141         } catch (NoSuchAlgorithmException e) {
142             e.printStackTrace();
143         } catch (ClientProtocolException e) {
144             e.printStackTrace();
145         } catch (ParseException e) {
146             e.printStackTrace();
147         } catch (IOException e) {
148             e.printStackTrace();
149         } finally {
150             httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
151             return responseContent;
152         }
153     }
154 }

 

posted @ 2016-03-23 12:24  魔流剑  阅读(1748)  评论(0编辑  收藏  举报