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();
Author by
user12707940
Updated on July 28, 2022Comments
-
user12707940 over 1 year
I am using RestTemplate
postForEntity
method toPOST
to an endpoint. IfPOST
is success, thestatusCode variable
should change its value to status code of201
, but I am having difficulty converting HttpStatus to int in Java. I am getting errorCannot 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 over 4 yearsBasically what I am trying to do is test
postForEntity
method, if it is success then status code should change to success which is201
-
rieckpil over 4 yearsthat does not reflect the question you asked
-
Jose Mhlanga almost 4 yearsUse More succinct and short
HttpStatus.OK.value();