https协议如何通过X509TrustManager接口实现自己创建的证书

quansheng2580 2009-12-22 02:17:27
开通了一个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)
...全文
10169 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangjunjin 2021-07-19
  • 打赏
  • 举报
回复

??????????????????????????????????????????????????????????????????????????????????

chinese_dingze 2010-07-07
  • 打赏
  • 举报
回复
我也在弄https,但是报的是Unexpected end of file from server,感觉是服务器给我们没有返回一样
quansheng2580 2009-12-22
  • 打赏
  • 举报
回复
在做证书的时候 已经把common name 设置为空了 因为这台服务器没有域名 所以就设置空 没有设置成IP
realreachard 2009-12-22
  • 打赏
  • 举报
回复
mark
临碣 2009-12-22
  • 打赏
  • 举报
回复
该不是因为证书里卖弄用的是hostname,你用的是ip吧?
听说这个对SSL来说有区别.

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧