Search code examples
javaspringhttp-status-codes

How to convert HttpStatus code to int in Java?


I am using RestTemplate postForEntity method to POST to an endpoint. If POST is success, the statusCode variable should change its value to status code of 201, but I am having difficulty converting HttpStatus to int in Java. I am getting error Cannot cast from HttpStatus to int I could not get any solutions regarding this. Any suggestions are appreciated.

Here is my code

import org.springframework.http.HttpStatus;

    public int postJson(Set<String> data) {
        int statusCode;
        try {

            ResponseEntity<String> result = restTemplate.postForEntity(url,new HttpEntity<>(request, getHttpHeaders()), String.class);

            statusCode = (int) result.getStatusCode();   

        } catch (Exception e) {
            LOGGER.error("No Post", e);
        }
        return statusCode;
    }
}


Solution

  • Or,

    you just use getStatusCodeValue() for short cut.

    import org.springframework.http.HttpStatus;
    
    public int postJson(Set<String> data) {
        int statusCode;
        try {
            ResponseEntity<String> result = restTemplate.postForEntity(url,new HttpEntity<>(request, getHttpHeaders()), String.class);
            statusCode = result.getStatusCodeValue();
        } catch (Exception e) {
            LOGGER.error("No Post", e);
        }
        return statusCode;
    }