Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Https Rest Service using Spring RestTemplate

Can anybody provide me with a code sample to access the rest service URL secured with HTTPS using the Spring Rest template?

I have the certificate, username and password. Basic Authentication is used on the server-side and I want to create a client that can connect to that server using a provided certificate, username and password (if needed).

like image 362
zdesam Avatar asked Jul 12 '13 16:07

zdesam


People also ask

Does RestTemplate support all HTTP methods?

Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods.


1 Answers

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File(keyStoreFile)),   keyStorePassword.toCharArray());  SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(   new SSLContextBuilder()     .loadTrustMaterial(null, new TrustSelfSignedStrategy())     .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())     .build(),     NoopHostnameVerifier.INSTANCE);  HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(   socketFactory).build();  ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(   httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); MyRecord record = restTemplate.getForObject(uri, MyRecord.class); LOG.debug(record.toString()); 
like image 103
Headroller Avatar answered Sep 21 '22 17:09

Headroller