如何验证 RestTemplate 响应?

Jot*_*thi 5 validation rest bean-validation resttemplate spring-boot

Spring 在控制器级别支持基于注解的验证。

(1) 是否有必要在 RestTemplate 级别对来自 REST 调用的响应进行此类验证?

如果答案是肯定的: (2) RestTemplate 是否会支持在未来某个时候验证来自 rest 调用的响应?

如果答案是否定的: (3) 为什么?

Ken*_*ynh 0

对我来说,问题很大。:)。据我了解,您想询问Spring可以支持的REST服务中的验证。

1. 是否有必要在 RestTemplate 级别对 REST 调用的响应进行此类验证?

实际上,这取决于您的应用程序或您的业务。您可以在控制器上执行,也可以在服务级别上执行,甚至可以执行自定义验证。对我来说,没有人强迫你做任何事。

然而,根据我的经验,我们应该肯定进行验证。所以我的回答是肯定的。

2. RestTemplate 是否会支持在将来某个时候验证来自其余调用的响应?

我想您想了解验证的详细信息?!正确的?Spring 支持很多事情来进行验证。对于简单的方法,您可以使用PathVariableor RequestParameter。例如:

@GetMapping("/test/{name}")
    private String test(@PathVariable(value = "name", required = true) String name){
        //...
    }
Run Code Online (Sandbox Code Playgroud)

Spring 将验证所有请求,并在所需参数丢失或类型错误时响应 400 Bad Request...

Spring还支持JSR 303 Bean验证:http://beanvalidation.org/1.0/spec/例如在这里:

public class MessageBean {
    @NotNull
    private String title;
    @NotNull
    private String message;
 
    // getters/setters/etc
}
Run Code Online (Sandbox Code Playgroud)

或者您想要执行自定义用户响应,例如:

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(MethodArgumentNotValidException exception) {
    //....
    return ErrorResponse.builder().message(errorMsg).build();
}
Run Code Online (Sandbox Code Playgroud)

这里有更多细节: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-validation

因此,这取决于需要我们在任何级别进行验证的业务。

3. 如果答案是否定的: (3) 为什么?

这个问题没必要回答。:)

希望有帮助

  • 感谢您的回答,但这不是我想要的。可能是我的问题不够清楚。我可以根据技术业务需求在任何层验证“请求”。我的问题_不是_关于验证请求。我的问题是“验证其他服务的响应”。 (2认同)