【发布时间】:2017-12-26 11:08:24
【问题描述】:
我正在编写调用一些后端 REST 服务的客户端。我正在发送 Product 对象,该对象将保存在 DB 中,并在响应正文中返回生成的 productId。
public Long createProduct(Product product) {
RestTemplate restTemplate = new RestTemplate();
final String url = " ... ";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Product> productEntity = new HttpEntity<>(product, headers);
try {
ResponseEntity<Product> responseEntity = restTemplate.postForEntity(url, productEntity, Product.class);
Product product = responseEntity.getBody();
return product.getProductId();
} catch (HttpStatusCodeException e) {
logger.error("Create product failed: ", e);
throw new CustomException(e.getResponseBodyAsString(), e, e.getStatusCode().value());
}
如果product 即responseEntity.getBody() 为空,这个product.getProductId() 看起来像潜在的NullPointerException,我应该以某种方式处理它吗?
我在互联网上查看了使用 RestTemplate postFprEntity、getForEntity 的示例......但没有找到任何处理 NPE 的示例。我想如果无法设置响应体,会抛出一些异常和状态码 5xx。
是否有可能当响应状态码为200时,那个body可以为空?
【问题讨论】:
-
是的,这是可能的。这一切都取决于从服务器端发送的内容
-
好的,谢谢。但是当我使用 curl 或 postman 调用此服务时,如果它返回状态 200,则总是有正文,即
Productjson。 -
不确定这里的问题是什么。让我总结一下我所说的。当响应代码为 200 时,body 可以为 null。为了处理这种情况,您需要在代码中通过检查它是否为 null 来处理它。但是如果从服务器端抛出异常而不是在返回 200 状态和正文为 null 的响应时抛出 5xx 异常
标签: spring resttemplate