简体   繁体   中英

How to use Apache Httpclient with Jersey 2.3 client

I would like to use an Apache connector with Jersey 2.3 client for HTTPS connections.

I tried the following:

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();

However, it seems the sslContext is ignored as the certificate of the server is rejected as untrusted (sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target)

If I remove the ".withConfig(clientConfig)" part, the SSL connection works fine, but evidently without the Apache connector. Is there a way to use my own ClientConfig with the Apache connector as well as my own SSLContext?

you need config SSL for apache connector.

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();

Not sure whay are you using apache connector. But you can make a client connection using jersey and https like this:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM