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
任意輸入,最后一個(gè)提示輸入回車(保證兩個(gè)密碼相等)否則tomcat不能啟動(dòng).
默認(rèn)生成的文件在用戶目錄下.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是剛才建立證書時(shí)候的名字
啟動(dòng)tomcat,訪問https:\\localhost:8443/如果能正常看到,說(shuō)明tomcat的https配置成功.
步驟四:
生成jdk能使用的證書
1,用ie導(dǎo)出證書(導(dǎo)出方法:http://www.ibm.com/developerworks/cn/opensource/os-httpclient/#N10114)
2,假設(shè)上邊導(dǎo)出文件的名字叫tt.cer
執(zhí)行(確保配置了java home)
keytool -import -noprompt -keystore D:\Java\jdk1.5.0_06\jre\lib\security\carcert -alias tomcat -file tt.cer –trustcacerts
其中紅色的部分替換成自己jre的路徑,alias同建立證書時(shí)的名字,file時(shí)剛才導(dǎo)出的證書的名字
會(huì)提示輸入密碼,輸入剛才建立證書時(shí)輸入的密碼
步驟五:
編寫代碼
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);
//設(shè)置成了默認(rèn)的恢復(fù)策略,在發(fā)生異常時(shí)候?qū)⒆詣?dòng)重試3次,在這里你也可以設(shè)置成自定義的恢復(fù)策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
//執(zhí)行g(shù)etMethod
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連接只有一個(gè)差距就是url