【问题标题】:Receive Spring ResponseEntity with and without body接收带有和不带有主体的 Spring ResponseEntity
【发布时间】:2021-07-06 09:36:10
【问题描述】:

如何实现有时不返回正文的 REST 调用?

我的 SpringBoot 应用程序通过 REST HTTP 调用外部服务,并通过 org.springframework.web.client 客户端和方法 public <T> ResponseEntity<T> exchange 实现。

到目前为止,客户端始终收到一个字符串主体 -> ResponseEntity<String>。前段时间我们调用的服务返回给我们HTTP 202没有正文,所以抛出以下异常:

java.lang.IllegalArgumentException: argument "content" is null.

如何让 Spring 忽略 202 状态代码的正文?

【问题讨论】:

  • 用您的自定义异常处理它。

标签: java spring spring-boot rest


【解决方案1】:

如果服务不返回响应正文,您可以使用Void 作为ResponseEntity 的泛型类型参数:

ResponseEntity<Void> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class)

如果服务有时会返回响应,您可以将响应作为String 处理。对于空响应,您将收到一个空字符串。对于非空响应,您需要自己反序列化返回的有效负载。

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class)
if (Strings.isEmpty(res.getBody())) {
    // handle empty response
} else {
    // handle non-empty response
}

【讨论】:

  • 感谢您的帖子。不幸的是,它不适合这个问题,因为服务确实返回响应,但没有正文 - 有时。
猜你喜欢
  • 2013-12-18
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多