milkamar
milkamar

Reputation: 453

Spring RestTemplate - Read different object type based on http status code?

I have client and server applications, both written in spring using Java. I am using RestTemplate to call server from client.

Server returns different response object, depending on result of operation.
Simplified code:

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); 
}

I want to be able to read those responses on client by status code,
but RestTemplate offers only to read one type, e.g. <Object_type>.class; and offers status code AFTER the .getForEntity(...) operation was executed - when response type is already returned.
What I want in pseudo code on client side:

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
     }
}

Is this possible in some non-hacky, clean way ? I read about setting response type as String.class and parse it afterwards, or reading Object.class (returns LinkedHashMap) and parse it.
Thanks for any tips.

Upvotes: 6

Views: 5738

Answers (1)

StanislavL
StanislavL

Reputation: 57381

I would suggest to introduce a common response which includes both ok and error (one of them is null)

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

and use it

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); 
}

and process the results

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();
     }
}

Upvotes: 1

Related Questions