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的最

终解决方案。

作者:magic_kid_2010,如果觉得笔者的博客对您有所帮助,欢迎【犒赏

发布了82 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/magic_kid_2010/article/details/101196939