通过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/如果能正常看到,说明tomcat的https配置成功.

步骤四:

生成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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值