Spring RestTemplate - 根据http状态代码读取不同的对象类型?

时间:2017-07-19 13:17:54

标签: java spring resttemplate

我有客户端和服务器应用程序,都是用Spring编写的。 我正在使用RestTemplate从客户端调用服务器。

服务器返回不同的响应对象,具体取决于操作结果。
简化代码:

public ResponseEntity<?> saveSomething (Object something) {
    boolean saved = save(something); //save logic
    if(saved)
        return new ResponseEntity<OKObject>(okObject,HttpStatus.OK);
    else
        return new ResponseEntity<ErrorObject>(errorObject,HttpStatus.FAILED); 
}

我希望能够通过状态代码在客户端上读取这些响应,但是RestTemplate仅提供读取一种类型,例如<Object_type>.class; 并在执行.getForEntity(...)操作后提供状态代码 -  何时返回响应类型。
在客户端伪代码我想要的是什么:

public void saveSomething(Object toSave) {
     ResTemplate template = new RestTemplate();
     ResponseEntity<Object> response = template.getForEntity(url,Object.class);
     if(response.getStatusCode() == HttpStatus.OK) {
         OKObject ok = (OKObject) response.getBody();
         //some work with ok object
     }
     if(response.getStatusCode() == HttpStatus.FAILED) {
         ErrorObject errorObject = (ErrorObject) response.getBody();
         //some work with errorObject
     }
}

这可能是以一种非黑客,干净的方式吗?我读到有关将响应类型设置为String.class并在之后解析,或阅读Object.class(返回LinkedHashMap)并解析它。
感谢您的任何提示。

1 个答案:

答案 0 :(得分:3)

我建议引入一个常见的响应,包括ok和error(其中一个为null)

publi class CommonResponseObject {
    private OKObject okObject;
    private ErrorObject errorObject;
    public CommonResponseObject(OKObject okObject) {
        this.okObject=okObject;
    }
    public CommonResponseObject(ErrorObject errorObject) {
        this.errorObject=errorObject;
    }
}

并使用它

public ResponseEntity<CommonResponseObject > saveSomething (Object something) {
    boolean saved = save(something); //save logic
    if(saved)
        return new ResponseEntity<>(new CommonResponseObject(okObject),HttpStatus.OK);
    else
        return new ResponseEntity<>(new CommonResponseObject(errorObject),HttpStatus.FAILED); 
}

并处理结果

public void saveSomething(Object toSave) {
     ResTemplate template = new RestTemplate();
     ResponseEntity<CommonResponseObject> response = template.getForEntity(url,CommonResponseObject.class);
     if(response.getStatusCode() == HttpStatus.OK) {
         OKObject ok = response.getBody().getOkObject();
     }
     if(response.getStatusCode() == HttpStatus.FAILED) {
         ErrorObject errorObject = response.getBody().getErrorObject();
     }
}