1. Overview
This article will demonstrate how to configure Apache HttpClient 4 to add SSL support. The purpose is simple----to request HTTPS URLs successfully without a valid certificate.
If you want to dig deeper and learn about other cool knowledge related to HttpClient, please click Httpclient-guide
Extended reading:
Httpclient-connection-management
Httpclient-advanced-config
Httpclient-4-cookies
2. Sslpeerunverifiedexception exception
With HttpClient if SSL is not configured, the following test----request an HTTPS URL----will fail:
1 Public classHttplivetest {2 3@Test (expected = sslpeerunverifiedexception.class)4 Public voidwhenhttpsurlisconsumed_thenexception ()5 throwsclientprotocolexception, IOException {6 7Defaulthttpclient httpClient =Newdefaulthttpclient ();8 String Urloverhttps9= "Https://localhost:8080/spring-security-rest-basic-auth";TenHttpGet GetMethod =NewHttpGet (URLOVERHTTPS); One AHttpResponse response =Httpclient.execute (GetMethod); -Assertthat (Response.getstatusline (). Getstatuscode (), Equalto (200)); - } the}
The specific exceptions are:
1 Javax.net.ssl.SSLPeerUnverifiedException:peer Not authenticated 2 At Sun.security.ssl.SSLSessionImpl.getPeerCertificates (sslsessionimpl.java:397)3at Org.apache.http.conn.ssl.AbstractVerifier.verify (abstractverifier.java:126)4...
The javax.net.ssl.SSLPeerUnverifiedException exception exception occurs whenever a URL cannot establish a valid chain of trust.
3. Configure Ssl--accept All (HttpClient version is less than 4.3)
The following configures the HTTP client to trust all chains (translator note: chains) whether they are valid or not.
1 @Test2 Public voidgivenacceptingallcertificates_whenhttpsurlisconsumed_thenexception ()3 throwsIOException, generalsecurityexception {4Truststrategy acceptingtruststrategy = (cert, authtype)true;5Sslsocketfactory SF =NewSslsocketfactory (6 acceptingtruststrategy, sslsocketfactory.allow_all_hostname_verifier);7Schemeregistry Registry =Newschemeregistry ();8Registry.register (NewScheme ("https", 8443, SF));9Clientconnectionmanager CCM =NewPoolingclientconnectionmanager (registry);Ten OneDefaulthttpclient httpClient =Newdefaulthttpclient (CCM); A - String Urloverhttps -= "HTTPS://LOCALHOST:8443/SPRING-SECURITY-REST-BASIC-AUTH/API/BARS/1"; theHttpGet GetMethod =NewHttpGet (URLOVERHTTPS); - -HttpResponse response =Httpclient.execute (GetMethod); -Assertthat (Response.getstatusline (). Getstatuscode (), Equalto (200)); +}
Under the new trust policy, overwrite the original standard certificate verification process (originally need to consult a configured trust manager)----The above test pass indicates that now the client can request the HTTPS URL.
4.spring resttemplate Configuration SSL (HttpClient version is less than 4.3)
We already know how to add SSL support to the native HttpClient configuration, and then look at the more Advanced Client----the Spring resttemplate.
Without SSL configured, as expected, the following tests will not pass:
1@Test (expected = resourceaccessexception.class)2 Public voidwhenhttpsurlisconsumed_thenexception () {3 String Urloverhttps4= "HTTPS://LOCALHOST:8443/SPRING-SECURITY-REST-BASIC-AUTH/API/BARS/1";5Responseentity<string>Response6=NewResttemplate (). Exchange (Urloverhttps, Httpmethod.get,NULL, String.class);7Assertthat (Response.getstatuscode (). Value (), Equalto (200));8}
Configure SSL below:
1 Import StaticOrg.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;2 Importjava.security.GeneralSecurityException;3 Importjava.security.cert.X509Certificate;4 ImportOrg.apache.http.auth.AuthScope;5 Importorg.apache.http.auth.UsernamePasswordCredentials;6 ImportOrg.apache.http.conn.scheme.Scheme;7 Importorg.apache.http.conn.ssl.SSLSocketFactory;8 ImportOrg.apache.http.conn.ssl.TrustStrategy;9 Importorg.apache.http.impl.client.DefaultHttpClient;Ten ImportOrg.springframework.http.HttpMethod; One Importorg.springframework.http.ResponseEntity; A Importorg.springframework.http.client.HttpComponentsClientHttpRequestFactory; - Importorg.springframework.web.client.ResourceAccessException; - Importorg.springframework.web.client.RestTemplate; the - ... - @Test - Public voidgivenacceptingallcertificates_whenhttpsurlisconsumed_thenexception () + throwsgeneralsecurityexception { - httpcomponentsclienthttprequestfactory requestfactory +=Newhttpcomponentsclienthttprequestfactory (); A defaulthttpclient httpClient at=(defaulthttpclient) requestfactory.gethttpclient (); -Truststrategy acceptingtruststrategy = (cert, authtype)true -Sslsocketfactory SF =NewSslsocketfactory ( - acceptingtruststrategy, allow_all_hostname_verifier); - Httpclient.getconnectionmanager (). Getschemeregistry () -. Register (NewScheme ("https", 8443, SF)); in - String Urloverhttps to= "HTTPS://LOCALHOST:8443/SPRING-SECURITY-REST-BASIC-AUTH/API/BARS/1"; +responseentity<string> response =Newresttemplate (requestfactory). -Exchange (Urloverhttps, Httpmethod.get,NULL, String.class); theAssertthat (Response.getstatuscode (). Value (), Equalto (200)); *}
As you can see, this is very similar to the native httpclient configuration SSL ----We added SSL support to the request factory and then initialized the template with the configured factory as the entry parameter.
5. Configure SSL (HttpClient version is 4.4)
In version 4.4, sslsocketfactoryis no longer used and can be easily configured as follows:
1 @Test2 Public voidGivenignoringcertificates_whenhttpsurlisconsumed_thencorrect ()3 throwsException {4Sslcontext Sslcontext =NewSslcontextbuilder ()5. Loadtrustmaterial (NULL, (certificate, AuthType)true). Build ();6 7Closeablehttpclient client =Httpclients.custom ()8 . Setsslcontext (Sslcontext)9. Setsslhostnameverifier (Newnoophostnameverifier ())Ten . Build (); OneHttpGet HttpGet =NewHttpGet (HOST_WITH_SSL); AHttpget.setheader ("Accept", "Application/xml"); - -HttpResponse response =Client.execute (httpget); theAssertthat (Response.getstatusline (). Getstatuscode (), Equalto (200)); -}
6.Spring resttemplate Configuring SSL (HttpClient 4.4)
We can configure the resttemplate in the same way:
1 @Test2 Public voidGivenacceptingallcertificatesusing4_4_whenusingresttemplate_thencorrect ()3 throwsclientprotocolexception, IOException {4 closeablehttpclient httpClient5=Httpclients.custom ()6. Setsslhostnameverifier (Newnoophostnameverifier ())7 . Build ();8 httpcomponentsclienthttprequestfactory requestfactory9=Newhttpcomponentsclienthttprequestfactory ();Ten requestfactory.sethttpclient (httpClient); One AResponseentity<string>Response -=Newresttemplate (requestfactory). Exchange ( -Urloverhttps, Httpmethod.get,NULL, String.class); theAssertthat (Response.getstatuscode (). Value (), Equalto (200)); -}
7. Summary
This tutorial discusses how to configure SSL for Apache HttpClient, ignoring the checksum to be able to access any HTTPS URL. and provide an example of configuring SSL for Spring Resttemplate.
It should be understood, however, that this policy completely ignores certificate validation, which can lead to security breaches and therefore can only be used where needed.
The sample code for this article provides access to the GitHub project, which is based on eclipse, so it can be easily imported and run.
8. Original Address:
Portal
Translation HttpClient Request HTTPS URL