跪求,第三天了,还没解决。。。httpClient访问https的问题。

from_null 2010-12-30 03:59:08


测试类1:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;

public class ZTest2 {
public static void main(String[] args) {
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();

httpClient.getHostConfiguration().setProxy("10.99.60.201",8080);

KeyStore keyStore = getKeyStore("D:/B/eps.keystore", "111111");
System.out.println("getSocketFactory****************");
SocketFactory socketFactory = null;
try {
socketFactory = new SSLSocketFactory(keyStore);
} catch (Exception e) {
e.printStackTrace();
}




// System.out.println("registryScheme****************");
// Scheme scheme = new Scheme("https", socketFactory, 80);
// ((ClientConnectionManager)httpClient.getHttpConnectionManager().).getSchemeRegistry().register(scheme);

// 创建GET方法的实例
GetMethod getMethod = new GetMethod("https://eps.dev.surepush.cn:443/epscu/");
// 使用系统提供的默认的恢复策略
//getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
try {
// 执行getMethod
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
}
// 读取内容
byte[] responseBody = getMethod.getResponseBody();
// 处理内容
System.out.println(new String(responseBody));
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("发生致命的异常,可能是协议不对或者返回的内容有问题!");
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
e.printStackTrace();
} finally {
// 释放连接
getMethod.releaseConnection();
}
}


public static KeyStore getKeyStore(String uri, String storepass) {
System.out.println("getKeyStore****************");
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
e.printStackTrace();
System.out.println("Failed to create keystore");
}
FileInputStream fis = null;
try {
fis = new FileInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File read exception");
}
try {
keyStore.load(fis, storepass.toCharArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keyStore;
}
}


以上代码抛如下异常:
log4j:WARN Error initializing output writer.
log4j:WARN Unsupported encoding?
log4j:WARN Error initializing output writer.
log4j:WARN Unsupported encoding?
getKeyStore****************
getSocketFactory****************
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1611)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1035)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:124)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1112)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:623)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at com.client.ctl.ZTest2.main(ZTest2.java:46)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:285)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:191)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1014)
... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:280)
... 23 more


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...全文
3909 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
from_null 2011-01-05
  • 打赏
  • 举报
回复
感谢楼上几位。
我已经搞定了,过程写在http://from-null.javaeye.com/admin/blogs/859795
有需要的可以去参考。结贴了。
qq443507232 2011-01-05
  • 打赏
  • 举报
回复
正在研究此问题 希望能有所沟通和交流
yangfeihu 2011-01-04
  • 打赏
  • 举报
回复
上面说了一大堆,没一个说到点子上。
1. 你访问的域名要与 要与 subject name 一样; (可以是IP)

2. 你要有(你访问网站)的跟证书.假设为ca.cer, 然后导入到名称为ca的keystore中(假设)
3.客户端需要制定trustStore, 如加入以下代码
System.setProperty("javax.net.ssl.trustStore", "c:\ca");
或是:
加入默认信任密钥库:keytool -import -keystore C:\Java\jdk1.6.0_14\jre\lib\security\cacerts -storepass changeit -file ca.cer -alias ca
这样就可以了.
还有, 我们之所以访问一些https网站,没有弹出错误提示,那是因为我们浏览器上有哪些网站的根证书.如:versign.cer,所以你用代码访问https网站,也是一样.

Jlins 2011-01-02
  • 打赏
  • 举报
回复
前天 刚学会使用httpclient访问https网站 不过我用的是httpclient 4的版本 ,楼主貌似是老版本的了...基本上处理流程如下 第一条最重要[Quote=引用 7 楼 swoky 的回复:]

1,证书的域名跟你程序中的域名一样(这个重要)
e.g.
keytool ...... -dname "CN=xxxx.com, OU=.........."

2,jdk中证书正确(你的getKeyStore方法没试过,一直是导入jdk的)

3,sun jdk中的https连接只能用域名的,不能用IP(配hosts也OK)
[/Quote]
swoky 2011-01-02
  • 打赏
  • 举报
回复
1,证书的域名跟你程序中的域名一样(这个重要)
e.g.
keytool ...... -dname "CN=xxxx.com, OU=.........."

2,jdk中证书正确(你的getKeyStore方法没试过,一直是导入jdk的)

3,sun jdk中的https连接只能用域名的,不能用IP(配hosts也OK)

reggiekiller 2010-12-31
  • 打赏
  • 举报
回复
以前搞过,复杂得很,就不添乱了
yaoweijq 2010-12-31
  • 打赏
  • 举报
回复
Exception in thread "main" javax.net.ssl.SSLException: hostname in certificate didn't match: <eps.dev.surepush.cn> != <*.xxxxxxx(公司名称).com>
程序中你访问的是
https://eps.dev.surepush.cn:443/epscu/
证书中的hostname是<*.xxxxxxx(公司名称).com>
二者不匹配,所以出异常了
你得先把二者搞匹配才行
把<*.xxxxxxx(公司名称).com>
映射到eps.dev.surepush.cn对应的IP可以尝试下
xiaochengfu1 2010-12-31
  • 打赏
  • 举报
回复
看得头晕
from_null 2010-12-30
  • 打赏
  • 举报
回复


测试类2:

public static void main(String[] args) throws Exception {

ZTest test = new ZTest();

//如果和服务器测试,就打开这两行
HttpHost proxy = new HttpHost("10.99.60.201", 8080);
test.getHttpClient().getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);

KeyStore keyStore = test.getKeyStore("D:/B/eps.keystore", "111111");
System.out.println("getSocketFactory****************");
SocketFactory socketFactory = null;
try {
socketFactory = new SSLSocketFactory(keyStore);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("registryScheme****************");
Scheme scheme = new Scheme("https", socketFactory, 80);
httpClient.getConnectionManager().getSchemeRegistry().register(scheme);

Protocol myhttps = new Protocol("https", new MySecureProtocolSocketFactory(), 443);
Protocol.registerProtocol("https ", myhttps);

// String url = "https://eps.dev.surepush.cn/epscu/log4j";
String url = "https://eps.dev.surepush.cn:443/epscu/";
HttpGet httpPost = new HttpGet(url);
// HttpPost httpPost = test.getHttpPost("http://localhost:8080/epscu/1.0/uploaditems");

// test.addFileBody(new String[] { "volumes" },
// new FileBody[] { new FileBody(new File("D:/D/SVN_EPS/multiuploadClient/src/volumes.xml"))});
//
// test.addContentBody("cpid", new StringBody("900", Charset.forName("utf-8")));
// test.addContentBody("uploadpassword", new StringBody("123456", Charset.forName("utf-8")));
// test.addContentBody("itemtype", new StringBody("0", Charset.forName("utf-8")));
// test.addContentBody("uploadtype", new StringBody("1", Charset.forName("utf-8")));

// test.setEntity(httpPost);

/***********************************************************************/

HttpResponse httpresponse = httpClient.execute(httpPost);

System.out.println("\n-------------------------------------------------------------\n");
HttpEntity httpentity = httpresponse.getEntity();

System.out.println("StatusLine" + httpresponse.getStatusLine());
if (httpentity != null) {
System.out.println("------------------Response content start------------------------");
try {
InputStream in = httpentity.getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
System.out.println(URLDecoder.decode(str, "utf-8"));
}
} catch (Exception e) {
e.printStackTrace();
}
// String responsesString=EntityUtils.toString(httpentity);
// System.out.println(responsesString);

System.out.println("--------------------Response content end----------------------");
System.out.println("Response Content-Type: "
+ httpentity.getContentType());
try {
httpentity.consumeContent();
} catch (IOException e) {
e.printStackTrace();
}
}
test.closeConnection();
}

这个类抛如下异常:
Exception in thread "main" javax.net.ssl.SSLException: hostname in certificate didn't match: <eps.dev.surepush.cn> != <*.xxxxxxx(公司名称).com>
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:220)
at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:149)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:130)
at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:399)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.updateSecureConnection(DefaultClientConnectionOperator.java:203)
at org.apache.http.impl.conn.AbstractPoolEntry.layerProtocol(AbstractPoolEntry.java:277)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.layerProtocol(AbstractPooledConnAdapter.java:138)
at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:704)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:421)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.client.ctl.ZTest.main(ZTest.java:195)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
大概意思我也能看懂,第一个异常是路径不匹配,我按照网上查找的方法,修改Windows\System32\drivers\etc\的文件夹,也改不对。
第二个异常不能识别证书,我按照https的路径,导了N次还是不对。
但问题就是没解决,郁闷死了,高人指点一下。。
我要解决办法啊啊啊。。。

81,122

社区成员

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

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