如何使用Apache Httpclient与Jersey 2.3客户端

时间:2013-09-28 00:25:18

标签: java apache ssl jersey

我想使用带有Jersey 2.3客户端的Apache连接器进行HTTPS连接。

我尝试了以下内容:

ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, new PoolingClientConnectionManager());

ApacheConnector connector = new ApacheConnector(clientConfig);  
clientConfig.connector(connector);  

Client client = ClientBuilder.newBuilder()
    .withConfig(clientConfig)
    .sslContext(sslContext)
    .hostnameVerifier(getHostnameVerifier())
    .build();

但是,似乎sslContext被忽略,因为服务器的证书被拒绝为不可信(sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径)

如果我删除“.withConfig(clientConfig)”部分,SSL连接工作正常,但显然没有Apache连接器。有没有办法将我自己的ClientConfig与Apache连接器以及我自己的SSLContext一起使用?

2 个答案:

答案 0 :(得分:4)

您需要为apache连接器配置SSL。

ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, new PoolingClientConnectionManager());
//config your ssl for apache connector
SslConfigurator sslConfig = SslConfigurator.newInstance();
clientConfig.property(ApacheClientProperties.SSL_CONFIG, sslConfig);

ApacheConnector connector = new ApacheConnector(clientConfig);  
clientConfig.connector(connector);  

Client client = ClientBuilder.newBuilder()
.withConfig(clientConfig)
.hostnameVerifier(getHostnameVerifier())
.build();

答案 1 :(得分:0)

不确定您使用的是apache连接器吗?但您可以使用jersey和https进行客户端连接,如下所示:

ClientConfig config = new DefaultClientConfig();
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, myTrustManager, null);
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx));
Client client = Client.create(config);