Comment contourner les erreurs de certificat SSL non valides avec Apache HttpClient 4.0?
Vous devez créer un SSLContext avec votre propre TrustManager et créer un schéma HTTPS utilisant ce contexte. Voici le code,
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
// Apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);
Toutes les autres réponses étaient obsolètes ou ne fonctionnaient pas pour HttpClient 4.3.
Voici un moyen d'autoriser tous les noms d'hôte lors de la construction d'un client http.
CloseableHttpClient httpClient = HttpClients
.custom()
.setHostnameVerifier(AllowAllHostnameVerifier.INSTANCE)
.build();
Ou, si vous utilisez la version 4.4 ou ultérieure, l'appel mis à jour se présente comme suit:
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
À titre d'information, il existe un moyen beaucoup plus simple d'accomplir la même chose avec HttpClient 4.1.
SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {
public boolean isTrusted(
final X509Certificate[] chain, String authType) throws CertificateException {
// Oh, I am easy...
return true;
}
});
Je viens juste de faire cela avec le plus récent HttpClient 4.5 et il semble qu'ils aient déconseillé un certain nombre de choses depuis la version 4.4. Voici l'extrait qui fonctionne pour moi et utilise la plus récente API:
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true)
.build();
return HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(
new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE))
.build()
))
.build();
Pour mémoire, testé avec httpclient 4.3.6 et compatible avec Executor of fluent api:
CloseableHttpClient httpClient = HttpClients.custom().
setHostnameVerifier(new AllowAllHostnameVerifier()).
setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
{
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
return true;
}
}).build()).build();
Pour Apache HttpClient 4.4:
HttpClientBuilder b = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSslcontext( sslContext);
// or SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
// allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
b.setConnectionManager( connMgr);
HttpClient client = b.build();
Ceci est extrait de notre implémentation de travail réelle.
Les autres réponses sont populaires, mais pour HttpClient 4.4, elles ne fonctionnent pas. J'ai passé des heures à essayer et à épuiser les possibilités, mais il semble y avoir eu un changement extrêmement important d'API et une relocalisation à 4.4.
Voir aussi une explication un peu plus complète sur: http://literatejava.com/networks/ignore-ssl-certificate-errors-Apache-httpclient-4-4/
J'espère que ça t'as aidé!
Apache HttpClient 4.5.5
HttpClient httpClient = HttpClients
.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
Aucune API obsolète n'a été utilisée.
Cas de test simple et vérifiable:
package org.Apache.http.client.test;
import org.Apache.http.HttpResponse;
import org.Apache.http.client.HttpClient;
import org.Apache.http.client.methods.HttpGet;
import org.Apache.http.client.methods.HttpUriRequest;
import org.Apache.http.conn.ssl.NoopHostnameVerifier;
import org.Apache.http.impl.client.HttpClients;
import org.Apache.http.ssl.SSLContextBuilder;
import org.junit.Before;
import org.junit.Test;
import Java.io.IOException;
import Java.security.KeyManagementException;
import Java.security.KeyStoreException;
import Java.security.NoSuchAlgorithmException;
public class ApacheHttpClientTest {
private HttpClient httpClient;
@Before
public void initClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
httpClient = HttpClients
.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
}
@Test
public void apacheHttpClient455Test() throws IOException {
executeRequestAndVerifyStatusIsOk("https://expired.badssl.com");
executeRequestAndVerifyStatusIsOk("https://wrong.Host.badssl.com");
executeRequestAndVerifyStatusIsOk("https://self-signed.badssl.com");
executeRequestAndVerifyStatusIsOk("https://untrusted-root.badssl.com");
executeRequestAndVerifyStatusIsOk("https://revoked.badssl.com");
executeRequestAndVerifyStatusIsOk("https://pinning-test.badssl.com");
executeRequestAndVerifyStatusIsOk("https://sha1-intermediate.badssl.com");
}
private void executeRequestAndVerifyStatusIsOk(String url) throws IOException {
HttpUriRequest request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assert statusCode == 200;
}
}
Si tout ce que vous voulez, c'est vous débarrasser des erreurs de nom d'hôte non valides, vous pouvez simplement le faire:
HttpClient httpClient = new DefaultHttpClient();
SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
.getSchemeRegistry().getScheme("https").getSocketFactory();
sf.setHostnameVerifier(new AllowAllHostnameVerifier());
Nous utilisons HTTPClient 4.3.5 et nous avons essayé presque toutes les solutions existent sur le stackoverflow mais rien, Après avoir réfléchi et résolu le problème, nous arrivons au code suivant qui fonctionne parfaitement, ajoutez-le simplement avant de créer une instance HttpClient.
une méthode à utiliser pour faire une demande de publication ....
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
HttpPost postRequest = new HttpPost(url);
continuez votre demande sous la forme normale
Avec couramment 4.5.2, je devais apporter la modification suivante pour que cela fonctionne.
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public Java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(sc).build();
String output = Executor.newInstance(httpClient).execute(Request.Get("https://127.0.0.1:3000/something")
.connectTimeout(1000)
.socketTimeout(1000)).returnContent().asString();
} catch (Exception e) {
}
Voici comment je l'ai fait -
Initialisation de DefaultHTTPClient -
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, new MockSSLSocketFactory()));
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
DefaultHttpClient httpclient = new DefaultHttpClient(cm);
Mock SSL Factory -
public class MockSSLSocketFactory extends SSLSocketFactory {
public MockSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(trustStrategy, hostnameVerifier);
}
private static final X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
@Override
public void verify(String Host, SSLSocket ssl) throws IOException {
// Do nothing
}
@Override
public void verify(String Host, X509Certificate cert) throws SSLException {
//Do nothing
}
@Override
public void verify(String Host, String[] cns, String[] subjectAlts) throws SSLException {
//Do nothing
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
private static final TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
}
Si derrière un proxy, besoin de le faire -
HttpParams params = new BasicHttpParams();
params.setParameter(AuthPNames.PROXY_AUTH_PREF, getClientAuthPrefs());
DefaultHttpClient httpclient = new DefaultHttpClient(cm, params);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(proxyUser, proxyPass));
DefaultHttpClient httpclient = new DefaultHttpClient();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
try {
sslContext.init(null,
new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
log.debug("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(
X509Certificate[] certs, String authType) {
log.debug("checkClientTrusted =============");
}
public void checkServerTrusted(
X509Certificate[] certs, String authType) {
log.debug("checkServerTrusted =============");
}
} }, new SecureRandom());
} catch (KeyManagementException e) {
}
SSLSocketFactory ssf = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.httpclient.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
} catch (Exception e) {
log.error(e.getMessage(),e);
}
En extension à réponse de ZZ Coder, il sera agréable de remplacer le nom d'hôte.
// ...
SSLSocketFactory sf = new SSLSocketFactory (sslContext);
sf.setHostnameVerifier(new X509HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
public void verify(String Host, String[] cns, String[] subjectAlts) throws SSLException {
}
public void verify(String Host, X509Certificate cert) throws SSLException {
}
public void verify(String Host, SSLSocket ssl) throws IOException {
}
});
// ...
Pour accepter tous les certificats dans HttpClient 4.4.x, vous pouvez utiliser le liner suivant lors de la création de httpClient:
httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build()).build();
Le code ci-dessous fonctionne avec 4.5.5
import Java.io.IOException;
import Java.security.KeyManagementException;
import Java.security.NoSuchAlgorithmException;
import Java.security.SecureRandom;
import Java.security.cert.CertificateException;
import Java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.Apache.http.client.methods.CloseableHttpResponse;
import org.Apache.http.client.methods.HttpGet;
import org.Apache.http.client.methods.HttpUriRequest;
import org.Apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.Apache.http.impl.client.CloseableHttpClient;
import org.Apache.http.impl.client.HttpClients;
import org.Apache.http.util.EntityUtils;
class HttpsSSLClient {
public static CloseableHttpClient createSSLInsecureClient() {
SSLContext sslcontext = createSSLContext();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() {
@Override
public boolean verify(String paramString, SSLSession paramSSLSession) {
return true;
}
});
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
}
private static SSLContext createSSLContext() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] {new TrustAnyTrustManager()}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return sslcontext;
}
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
}
public class TestMe {
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpsSSLClient.createSSLInsecureClient();
CloseableHttpResponse res = client.execute(new HttpGet("https://wrong.Host.badssl.com/"));
System.out.println(EntityUtils.toString(res.getEntity()));
}
}
La sortie du code est
La sortie sur le navigateur est
Le pom utilisé est ci-dessous
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.Apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.Apache.org/POM/4.0.0 http://maven.Apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tarun</groupId>
<artifactId>testing</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.Apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.Apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.Apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
</dependencies>
</project>
Si vous utilisez API fluide , vous devez le configurer via la variable Executor
:
Executor.unregisterScheme("https");
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));
... où sslContext
est le contexte SSLC créé comme indiqué dans la réponse du ZZ Coder .
Après cela, vous pouvez faire vos requêtes http en tant que:
String responseAsString = Request.Get("https://192.168.1.0/whatever.json")
.execute().getContent().asString();
Remarque: testé avec HttpClient 4.2
Testé avec HttpClient 4.5.5 avec l'API Fluent
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext).build();
String result = Executor.newInstance(httpClient)
.execute(Request.Get("https://localhost:8080/someapi")
.connectTimeout(1000).socketTimeout(1000))
.returnContent().asString();
une version de travail complète pour Apache HttpClient 4.1.3 (basée sur le code d'oleg ci-dessus, mais il lui fallait toujours un allow_all_hostname_verifier sur mon système):
private static HttpClient trustEveryoneSslHttpClient() {
try {
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() {
public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
// Oh, I am easy...
return true;
}
}, org.Apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", 443, socketFactory));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
DefaultHttpClient client = new DefaultHttpClient(mgr, new DefaultHttpClient().getParams());
return client;
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
Remarque: je rejette toutes les exceptions car, en réalité, je ne peux rien faire si l'un de ces problèmes échoue dans un système réel!
Testé avec 4.3.3
import Java.security.KeyManagementException;
import Java.security.KeyStoreException;
import Java.security.NoSuchAlgorithmException;
import Java.security.SecureRandom;
import Java.security.cert.CertificateException;
import Java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.Apache.http.Header;
import org.Apache.http.HttpEntity;
import org.Apache.http.client.methods.CloseableHttpResponse;
import org.Apache.http.client.methods.HttpGet;
import org.Apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.Apache.http.conn.ssl.SSLContexts;
import org.Apache.http.conn.ssl.TrustStrategy;
import org.Apache.http.impl.client.CloseableHttpClient;
import org.Apache.http.impl.client.HttpClients;
import org.Apache.http.util.EntityUtils;
public class AccessProtectedResource {
public static void main(String[] args) throws Exception {
// Trust all certs
SSLContext sslcontext = buildSSLContext();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://yoururl");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
for (Header header : response.getAllHeaders()) {
System.out.println(header);
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
private static SSLContext buildSSLContext()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException {
SSLContext sslcontext = SSLContexts.custom()
.setSecureRandom(new SecureRandom())
.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
})
.build();
return sslcontext;
}
}
Testé sur 4.5.4:
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext)
.build();
fwiw, un exemple utilisant l’implémentation "RestEasy" de JAX-RS 2.x pour construire un client spécial "Trust All" ...
import Java.io.IOException;
import Java.net.MalformedURLException;
import Java.security.GeneralSecurityException;
import Java.security.KeyManagementException;
import Java.security.KeyStoreException;
import Java.security.NoSuchAlgorithmException;
import Java.security.cert.CertificateException;
import Java.security.cert.X509Certificate;
import Java.util.ArrayList;
import Java.util.Arrays;
import javax.ejb.Stateless;
import javax.net.ssl.SSLContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.Apache.logging.log4j.LogManager;
import org.Apache.logging.log4j.Logger;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.Apache.http.config.Registry;
import org.Apache.http.config.RegistryBuilder;
import org.Apache.http.conn.HttpClientConnectionManager;
import org.Apache.http.conn.ssl.TrustStrategy;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.Apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.Apache.http.conn.socket.ConnectionSocketFactory;
import org.Apache.http.conn.ssl.NoopHostnameVerifier;
import org.Apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.Apache.http.impl.client.CloseableHttpClient;
import org.Apache.http.impl.client.HttpClientBuilder;
import org.Apache.http.ssl.SSLContexts;
@Stateless
@Path("/postservice")
public class PostService {
private static final Logger LOG = LogManager.getLogger("PostService");
public PostService() {
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public PostRespDTO get() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException, GeneralSecurityException {
//...object passed to the POST method...
PostDTO requestObject = new PostDTO();
requestObject.setEntryAList(new ArrayList<>(Arrays.asList("ITEM0000A", "ITEM0000B", "ITEM0000C")));
requestObject.setEntryBList(new ArrayList<>(Arrays.asList("AAA", "BBB", "CCC")));
//...build special "trust all" client to call POST method...
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(createTrustAllClient());
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
ResteasyWebTarget target = client.target("https://localhost:7002/postRespWS").path("postrespservice");
Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(requestObject, MediaType.APPLICATION_JSON));
//...object returned from the POST method...
PostRespDTO responseObject = response.readEntity(PostRespDTO.class);
response.close();
return responseObject;
}
//...get special "trust all" client...
private static CloseableHttpClient createTrustAllClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUSTALLCERTS).useProtocol("TLS").build();
HttpClientBuilder builder = HttpClientBuilder.create();
NoopHostnameVerifier noop = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, noop);
builder.setSSLSocketFactory(sslConnectionSocketFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
}
private static final TrustStrategy TRUSTALLCERTS = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
}
dépendances Maven liées
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.Apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
Si vous rencontrez ce problème lors de l'utilisation d'AmazonS3Client, qui intègre Apache HttpClient 4.1, il vous suffit de définir une propriété système comme celle-ci afin que le vérificateur de certificats SSL soit assoupli:
-Dcom.amazonaws.sdk.disableCertChecking = true
Méfait géré