我有客户端和服务器应用程序,都在春季使用Java编写.
我正在使用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)并对其进行解析.
感谢您的提示.
解决方法:
我建议介绍一个常见的响应,其中包括确定和错误(其中一个为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();
}
}