今天在使用Rest-Assured测试登录相关的功能,中间涉及到了HTTPS协议,当然,测试环境中的Certificate是自己定义的,还有一个是已经过期的!使用Rest-Assured访问的时候提示证书过期等各种问题。
花了点时间研究了一下,当然没有研究透彻,只是让它可以工作,留待后面专门研究HTTPS的整个连接创建流程后再补充完整吧。
这里说的两种方式,主要看客户端,如果只是用Java自带的HttpURLConnection等与HTTPS协议的server交互,则可以采用下面第一种方式来接受server的Certificates;如果采用的是Apache Http Client或者各种使用Apache Http Client作为底层交互的工具(如Rest-Assured),需要接受Server Certificates时,可以采用第二种方式:
- 1,客户端采用HttpURLConnection方式:
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// do nothing
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// do nothing
}
}};
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}