Spring Boot RestTemplate 常用操作

1、身份证验证。

RestTemplate restTemplate = new RestTemplate();
 
// set username/password for http basic authentication
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("username","password"));

2、添加任意的请求头格式。

RestTemplate 默认只支持 application/json 和 application/*+json 格式的请求头。

RestTemplate restTemplate = new RestTemplate();
 
// set content-type=application/json http header
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
    return execution.execute(request, body);
  }
});
    

3、设置 Cookie 和 Header。

具体见另一篇博文 Spring RestTemplate with Cookie and Header

4、绕过 HTTPS 错误:java.security.cert.CertificateException: No name matching <some url> found

当使用RestTemplate通过协议https访问资源时,可能会出现类似 "java.security.cert.CertificateException" 的异常。这是因为Java

应用程序在其密钥库中没有正确的证书。作为开发人员,您可能不想在有人进行CA程序时被阻止。您可以继续忽略此 SSL 主机

验证,如下所示。但这只是一个临时解决方案,不应在任何生产环境中使用。

@Configuration
public class ByPassSSLVerificationConfig {
  // This RestTemplate actually ignore the SSL hostname verification
  @Bean
  public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier allPassVerifier = (String s, SSLSession sslSession) -> true;  // ignore hostnaem checking
 
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy).build(); // keystore is null, not keystore is used at all
 
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, allPassVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
 
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
  }
}

然后注入 RestTemplate Bean,并发送https请求,该异常将消失。但是请注意,这只是一个绕过,不是针对此Exception的最

终解决方案。

一起学习

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

magic_kid_2010

你的支持将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值