https协议如何通过X509TrustManager接口实现自己创建的证书
开通了一个https协议,但是不是国际认证的,自己做的证书,访问一个接口的时候比如 https:/xx.xx.xx.xx/a?c=d的时候,如果在游览器访问,需要用户确认的。如果我要模拟服务器向这个接口发送请求,就会报错误。
我的原代码是:
进入servlet调用该方法
public void htts() {
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
// 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
URL reqURL = new URL(
"https:/xx.xx.xx.xx/a?c=d"); // 创建URL对象
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL
.openConnection();
httpsConn.setSSLSocketFactory(ssf);
httpsConn.disconnect();
/*
* 下面这段代码实现向Web页面发送数据,实现与网页的交互访问 httpsConn.setDoOutput(true);
* OutputStreamWriter out = new
* OutputStreamWriter(huc.getOutputStream(), "8859_1"); out.write(
* "……" ); out.flush(); out.close();
*/
// 取得该连接的输入流,以读取响应内容
InputStreamReader insr = null;
insr = new InputStreamReader(httpsConn.getInputStream());
// 读取服务器的响应内容并显示
int respInt = 0;
respInt = insr.read();
while (respInt != -1) {
System.out.print((char) respInt);
respInt = insr.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
MyX509TrustManager类 就是实现接口
public class MyX509TrustManager implements X509TrustManager{
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
public boolean isClientTrusted(X509Certificate[] arg0) {
// TODO Auto-generated method stub
return true;
}
public boolean isServerTrusted(X509Certificate[] arg0) {
// TODO Auto-generated method stub
return true;
}
}
但是会报错误,请高手解决 谢谢
错误信息如下:
java.io.IOException: HTTPS hostname wrong: should be <调用的服务器的IP地址>
at sun.net.www.protocol.https.HttpsClient.checkURLSpoofing(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)