Java 如何使用 Spring RestTemplate 调用 HTTPS RESTful Web 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42323468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:03:03  来源:igfitidea点击:

How to call HTTPS restful web services using Spring RestTemplate

javaspringrestresttemplate

提问by user1272936

I am using Tomcat7, Spring framework for ReST web services. I am trying to call an httpsweb service using Spring RestTemplate. I am getting the following error:

我正在使用 Tomcat7,ReST Web 服务的 Spring 框架。我正在尝试使用Spring RestTemplate调用httpsWeb 服务。我收到以下错误:

unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

无法找到到请求目标的有效认证路径;嵌套异常是 javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效认证路径

I check online at stackoverflow. I tried the sample code from the url: Access Https Rest Service using Spring RestTemplate

我在stackoverflow上在线查看。我尝试了 url 中的示例代码: Access Https Rest Service using Spring RestTemplate

I couldn't get it to work. Can anybody please tell me based on the code below what do I need to change? Also can anybody tell me or provide me with the pom.xml file which java libraries would I need?

我无法让它工作。有人可以根据下面的代码告诉我我需要更改什么吗?也有人可以告诉我或向我提供我需要哪些 Java 库的 pom.xml 文件吗?

        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.client.RestTemplate;

        import com.fasterxml.Hymanson.core.JsonGenerationException;
        import com.fasterxml.Hymanson.databind.JsonMappingException;
        import com.fasterxml.Hymanson.databind.ObjectMapper;
        import com.journaldev.spring.controller.EmpRestURIConstants;
        import com.journaldev.spring.model.CostControlPost;
        import com.journaldev.spring.model.Employee;
        import com.journaldev.spring.model.RfxForUpdate;

        import static org.junit.Assert.*;
        import org.apache.commons.codec.binary.Base64;


        import javax.net.ssl.*;
        import java.io.*;
        import java.security.KeyStore;
        import java.security.MessageDigest;
        import java.security.cert.CertificateException;
        import java.security.cert.X509Certificate;


        public class TestExample2
        {
            public static final String SERVER_LIST="https://abc/sourcing/testServices";


            @Test
            public void testGetListOfServiceNames()
            {
                try
                {


                    RestTemplate restTemplate = new RestTemplate();
                    ResponseEntity<String> response = restTemplate.exchange(SERVER_LIST,HttpMethod.GET,null,String.class);
                    assertNotNull(response);    
                }
                catch(Exception e)
                {
                    System.out.println("e:"+e.getMessage());
                }
            }


        }

回答by user1211

Either you need to have certificates in your keystore or you can accept all certificates (kind off ignore certificate validation)

您需要在密钥库中拥有证书,或者您可以接受所有证书(忽略证书验证)

So you can re-define bean of rest template as

所以你可以将休息模板的bean重新定义为

import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import java.security.cert.X509Certificate;

@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(csf)
                    .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
 }

You should not need additional jars except for apache core, client and dependencies.

除了 apache 核心、客户端和依赖项之外,您不需要额外的 jar。