user12707940
user12707940

Reputation: 161

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

Upvotes: 2

Views: 26539

Answers (2)

Junyoung Oh
Junyoung Oh

Reputation: 106

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

Upvotes: 2

rieckpil
rieckpil

Reputation: 12021

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

Upvotes: 2

Related Questions