【问题标题】:Does REST (RestTemplate) in Spring Library support HTTPS protocol?Spring库中的REST(RestTemplate)是否支持HTTPS协议?
【发布时间】:2012-12-06 23:36:34
【问题描述】:

我正在尝试通过 HTTPS 连接到 Web 服务器,但 response.getBody() 返回 null 但是我想返回 JSON 数组。 statusCode 是 200,并且标头包含正确的信息,但响应正文是 null。为此,我使用标准 Spring RestTemplate API,特别是 postForEntity()。也许为了做到这一点,我必须使用一些特殊的 Spring API?

很遗憾,我在 Spring REST 文档中找不到任何关于 HTTPS 支持和 SSL/'TLS' 证书的信息(它非常有限)。

【问题讨论】:

  • “无法得到任何回应”究竟是什么意思?有错误代码吗?
  • 好的,响应的状态码是什么?如果是“200”,请求本身应该没问题。您可以在服务器端验证您发送请求的方式通常有效吗?例如,尝试使用您的网络浏览器调用您的应用程序调用的 url。

标签: java spring rest https


【解决方案1】:

您可以将RestTemplate配置为HttpComponentsClientHttpRequestFactory,例如:

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

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

这允许RestTemplate 在后台使用Apache HttpComponents HttpClient,这绝对支持 SSL。

看起来HttpComponentsClientHttpRequestFactory提供的HttpClient支持开箱即用的SSL,所以你这边可能几乎不需要配置。

【讨论】:

  • @AlexanderKaraberov 您可以将其添加到应用程序上下文中,也可以以编程方式创建对象,例如new RestTemplate(...) 我只是使用了一个典型的 xml 示例。不幸的是,我无法评论 Android,我在那里没有太多经验。 :-)
  • @AlexanderKaraberov 我不知道这个变化,我已经更新了我的答案。希望对您有所帮助。
  • @AlexanderKaraberov 没问题,很高兴我能以某种方式提供帮助。
  • @Jonathan,我如何通过 new RestTemplate(...) 实现这个工厂?我应该在 RestTemplate() 里面放什么?
  • @Alexandre Java 中的等价物是:new RestTemplate(new HttpComponentsClientHttpRequestFactory())。如果您需要进一步的帮助,我建议您将其作为新问题提出 - 您至少会得到更及时的回复。 :-)
猜你喜欢
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2012-07-09
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
相关资源
最近更新 更多