使用 Spring RestTemplate 访问 Https Rest Service [英] Access Https Rest Service using Spring RestTemplate

查看:42
本文介绍了使用 Spring RestTemplate 访问 Https Rest Service的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我提供一个代码示例来访问使用 Spring Rest 模板通过 HTTPS 保护的 rest 服务 URL?

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

推荐答案

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

这篇关于使用 Spring RestTemplate 访问 Https Rest Service的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆