httpclient发送https请求

一,java使用 keytool工具创建证书

     CMD窗口中运行 "keytool -genkey -alias "别名" -keyalg RSA -validity "有效时间" -keystore "生成证书路径"

二,配制tomcat支持ssl

            在tomcat的config server.xml中打开 Connector结点

  <Connector port="443" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true" 
               keystoreFile="yourPath/xx.keystore" keystorePass="yourPwd"
               clientAuth="false" sslProtocol="TLS" />
    

 这里注意下,在tomcat6下

 protocol="HTTP/1.1 "    
<!-- 改为 -->
 protocol="org.apache.coyote.http11.Http11Protocol"

否则起动会报错

三,工程中web.xml配制

            上两部己实现了ssl的访问 https://localst (443为https默认端口所以不用加端口号)就己是ssl安全通道中,但是我们还是可以通过http://localhost:port 访问,这里要让它http时自动成https

            在web.xml中加入下面内容

<security-constraint>
 	<web-resource-collection>
 		<web-resource-name>SSL</web-resource-name>
 		<url-pattern>/xxx/*</url-pattern>
 	</web-resource-collection>
 	<user-data-constraint>
 		<transport-guarantee>CONFIDENTIAL</transport-guarantee>
 	</user-data-constraint>
 </security-constraint>

 在url-pattern中配制的是你要拦截的请求路径,比如只想对login模块强制转成https,则可配 /login/*

四,此时让tomcat支持https己全部配制完成,浏览器第一次访问时因为是自己制作的证书可以会有安全信任问题,要添加例外。想要httpclient发送https的请求,则还需如下的步骤

五,从浏览器中导出让才的证书(crt,pem后缀都可以)然后用keytool工具导入keystore,命令如下:

     keytool -import -alias "localhost" -file xxx.crt -keystore ooo.keystore

xxx.crt            : 刚从浏览器导出的证书

ooo.keystore  :命令生成的keystore文件

六,java代码 (不得不说httpclient3和4版本在使用上差异还很大,用习惯了3总感觉4并不太顺手)

public static String sendSSLRequest(String requestUrl) {  
    long responseLength = 0; // 响应长度
    String responseContent = null; // 响应内容
    HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
    KeyStore trustStore = null;  
    InputStream fis = null;  
    HttpGet httpGet = null;  
    HttpResponse response = null;  
    try {  
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
        fis = HttpsBaseAction.class.getClassLoader().getResourceAsStream(  
                "my.keystore");  
        trustStore.load(fis, "pwd".toCharArray()); // 加载KeyStore

        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); // 创建Socket工厂,将trustStore注入
        Scheme sch = new Scheme("https", 443, socketFactory); // 创建Scheme
        httpClient.getConnectionManager().getSchemeRegistry().register(sch); // 注册Scheme
        httpGet = new HttpGet(requestUrl); // 创建HttpGet

        Header headers[] = { new BasicHeader("myheader", "value") };  
        httpGet.setHeaders(headers); // 设置头信息
         // 设置请求参数,get好像只能在url那里用?xx=xx传参(暂时没找到到别的可传参方法)

        // 如用post传参如下
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();    
        formparams.add(new BasicNameValuePair("prameName", "value"));    
        UrlEncodedFormEntity uefEntity;    
        uefEntity = new UrlEncodedFormEntity(formparams,  HTTP.UTF_8);    
                    HttpPost post = new HttpPost(requestUrl);  
        post.setEntity(uefEntity);  
        post.setHeader("myheader", "value");  
      
                    // response = httpClient.execute(post); // 执行POST请求
        response = httpClient.execute(httpGet); // 执行GET请求
        HttpEntity entity = response.getEntity(); // 获取响应实体
        if (null != entity) {  
            responseLength = entity.getContentLength();  
            responseContent = EntityUtils.toString(entity, "UTF-8");  
            EntityUtils.consume(entity); // Consume response content
        }  

        System.out.println("请求地址: " + httpGet.getURI());  
        System.out.println("响应状态: " + response.getStatusLine());  
        System.out.println("响应长度: " + responseLength);  
        System.out.println("响应内容: " + responseContent);  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        try {  
            fis.close();  
        } finally {  
            httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
            return responseContent;  
        }  
    }  
}  

猜你喜欢

转载自fhqibjg.iteye.com/blog/1567543