Does REST (RestTemplate) in Spring Library support

2019-03-15 19:20发布

问题:

I'm trying to connect to the web server via HTTPS protocol, but response.getBody() returns null and have to return a JSON array. statusCode is 200 and headers contain correct information, only body is null. I use standard Spring RestTemplate API for this purpose (postForEntity()). Maybe in order to do this I have to use some special Sping API?

Unfortunately I couldn't find any information about HTTPS support and SSL/'TLS' certificates in Spring REST documentation (it is quite limited).

回答1:

You can configure the RestTemplate with the HttpComponentsClientHttpRequestFactory, for example:

<bean id="httpComponentsClientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"/>

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <constructor-arg ref="httpComponentsClientHttpRequestFactory"/>
</bean>

That allows the RestTemplate to use the Apache HttpComponents HttpClient under the hood, which definitely supports SSL.

It looks like the HttpClient provided by HttpComponentsClientHttpRequestFactory supports SSL out of the box, so there may be almost no configuration required on your side.