How to convert HttpStatus code to int in Java?

11,472

Solution 1

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

Solution 2

The Spring Framework returns an Enum with the HttpStatus:

public class ResponseEntity<T> extends HttpEntity<T> {

    /**
     * Return the HTTP status code of the response.
     * @return the HTTP status as an HttpStatus enum entry
     */
    public HttpStatus getStatusCode() {
        if (this.status instanceof HttpStatus) {
            return (HttpStatus) this.status;
        }
        else {
            return HttpStatus.valueOf((Integer) this.status);
        }
    }
}

And the enum is defined as the following:

public enum HttpStatus {

    // 1xx Informational

    /**
     * {@code 100 Continue}.
     * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.2.1">HTTP/1.1: Semantics and Content, section 6.2.1</a>
     */
    CONTINUE(100, "Continue"),

   // ...
}

So you can obtain the status as an int as the following:

int statusCode = result.getStatusCode().value(); 
Share:
11,472
user12707940
Author by

user12707940

Updated on July 28, 2022

Comments

  • user12707940
    user12707940 over 1 year

    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;
        }
    }
    
    
  • user12707940
    user12707940 over 4 years
    Basically what I am trying to do is test postForEntity method, if it is success then status code should change to success which is 201
  • rieckpil
    rieckpil over 4 years
    that does not reflect the question you asked
  • Jose Mhlanga
    Jose Mhlanga almost 4 years
    Use More succinct and short HttpStatus.OK.value();