DANCE WITH JAVA

开发出高质量的系统

常用链接

统计

积分与排名

好友之家

最新评论

通过httpClient连接 tomcat https (ssl)

 

HttpClient连接tomcat https(使用私有证书)

步骤一:

www.apache.org下载所需的类包

commons-codec-1.3.jar

commons-httpclient-3.1-rc1.jar

commons-logging.jar

步骤二:

制作证书:

keytool -genkey -alias tomcat -keyalg RSA

任意输入,最后一个提示输入回车(保证两个密码相等)否则tomcat不能启动.

默认生成的文件在用户目录下.keystore

步骤三:

配置tomcat

更改tomcat配置文件server.xml

加入

<Connector port="8443" maxHttpHeaderSize="8192"

               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"

               enableLookups="false" disableUploadTimeout="true"

               acceptCount="100" scheme="https" secure="true"

               clientAuth="false" sslProtocol="TLS"

                        keystoreFile="C:\.keystore"   keystorePass="123456"

                        />

其中keystoreFile是刚生成文件的带全路径的名字

keystorePass是刚才建立证书时候的名字

启动tomcat,访问https:\\localhost:8443/如果能正常看到,说明tomcathttps配置成功.

步骤四:

生成jdk能使用的证书
 1,用ie导出证书(导出方法:http://www.ibm.com/developerworks/cn/opensource/os-httpclient/#N10114)

2,假设上边导出文件的名字叫tt.cer

执行(确保配置了java  home)

keytool -import -noprompt -keystore D:\Java\jdk1.5.0_06\jre\lib\security\carcert -alias tomcat -file tt.cer –trustcacerts

其中红色的部分替换成自己jre的路径,alias同建立证书时的名字,file时刚才导出的证书的名字

 

会提示输入密码,输入刚才建立证书时输入的密码

 

步骤五:

编写代码

 

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class Test {
    
public static void main(String[] args) throws Exception{
//        normal();
        ssl();

    }

    
public static void ssl()throws Exception{
        String url 
= "https://127.0.0.1:8443/ts/";
        get(url);
    }

    
public static void normal()throws Exception{
        String url 
= "http://127.0.0.1:8080/ts/";
        get(url);
    }

    
public static void get(String url) throws Exception{
        HttpClient client 
= new HttpClient();
        GetMethod getMethod 
= new GetMethod(url);
        
//设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
                    
new DefaultHttpMethodRetryHandler()); 
        
//执行getMethod
        int statusCode = client.executeMethod(getMethod);
        
if (statusCode != HttpStatus.SC_OK) {
          System.err.println(
"Method failed: " + getMethod.getStatusLine());
        }

        
byte[] responseBody = getMethod.getResponseBody();
        System.out.println(
new String(responseBody));
        getMethod.releaseConnection();
    }

}

 

普通连接和ssl连接只有一个差距就是url

 

 

posted on 2007-07-27 18:01 dreamstone 阅读(7624) 评论(0)  编辑  收藏 所属分类: 利器其它开源框架


只有注册用户登录后才能发表评论。


网站导航: