我在Tomcat上设置了SSL,端口8080上的http和端口8443上的https都可以直接访问,我从应用程序API获得了所需的响应。当我使用以下Spring代码访问相同的API时,我得到NULL。
Foo mc = restTemplate.getForObject("http://" + hostName + ":8080" + "/foo" , Foo.class);
未设置SSL时代码有效。
如何解决这个问题?
答案 0 :(得分:1)
我设法让它运作起来。为了其他人的利益,我列出了以下步骤。
首先,我在this tutoiral的Spring SpringTemplate和SSL(HttpClient 4.4)部分添加代码。 (我有HttpClient 4.5.4)。通过此更改,当我点击Rest API的URL时出现以下异常:
I/O error on GET request for "http://localhost:8080/foo":
sun.security.validator.ValidatorException:
PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException:
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 targe
其次,为了解决上面提到的异常,我遵循了mkyong的tutorial。顺便说一句,Java程序的链接不再有效。我需要从其他地方找到它。
答案 1 :(得分:0)
您需要为HTTPS配置RestTemplate
以下是您的案例的测试结果的示例
@Test
public void httpsTest() throws GeneralSecurityException {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory.getHttpClient();
TrustStrategy acceptingTrustStrategy = (cert, authType) -> true
SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy,
ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient.getConnectionManager().getSchemeRegistry()
.register(new Scheme("https", 8443, sf));
String urlOverHttps = "https://" + hostName + ":8080" + "/foo";
ResponseEntity<String> response = new RestTemplate(requestFactory).
exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}