如何在Java中将HttpStatus代码转换为int?
我正在使用restemplate如何在Java中将HttpStatus代码转换为int?,java,spring,http-status-codes,Java,Spring,Http Status Codes,我正在使用restemplatepostForEntity方法将POST发布到端点。如果POST成功,则statusCode变量应将其值更改为201的状态代码,但我在Java中将HttpStatus转换为int时遇到困难。我收到错误无法从HttpStatus转换为int我无法获得任何有关此问题的解决方案。如有任何建议,我们将不胜感激 这是我的密码 import org.springframework.http.HttpStatus; public int postJson(Set<
postForEntity
方法将POST
发布到端点。如果POST
成功,则statusCode变量
应将其值更改为201
的状态代码,但我在Java中将HttpStatus转换为int时遇到困难。我收到错误无法从HttpStatus转换为int
我无法获得任何有关此问题的解决方案。如有任何建议,我们将不胜感激
这是我的密码
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;
}
}
import org.springframework.http.HttpStatus;
公共int-postJson(设置数据){
int状态码;
试一试{
ResponseEntity result=restTemplate.postForEntity(url,新的HttpEntity(请求,getHttpHeaders()),String.class);
statusCode=(int)result.getStatusCode();
}捕获(例外e){
记录器错误(“无Post”,e);
}
返回状态码;
}
}
Spring框架返回一个带有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);
}
}
}
Spring框架返回一个带有
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);
}
}
}
或者
您只需使用getStatusCodeValue()
作为捷径
import org.springframework.http.HttpStatus;
公共int-postJson(设置数据){
int状态码;
试一试{
ResponseEntity result=restTemplate.postForEntity(url,新的HttpEntity(请求,getHttpHeaders()),String.class);
statusCode=result.getStatusCodeValue();
}捕获(例外e){
记录器错误(“无Post”,e);
}
返回状态码;
}
或
您只需使用getStatusCodeValue()
作为捷径
import org.springframework.http.HttpStatus;
公共int-postJson(设置数据){
int状态码;
试一试{
ResponseEntity result=restTemplate.postForEntity(url,新的HttpEntity(请求,getHttpHeaders()),String.class);
statusCode=result.getStatusCodeValue();
}捕获(例外e){
记录器错误(“无Post”,e);
}
返回状态码;
}
基本上我想做的是测试postForEntity
方法,如果是成功,那么状态代码应该改为success,即201
,它不反映你问的问题。基本上我想做的是测试postForEntity
方法,如果是success,则状态代码应更改为success,即201
,它不反映您提出的问题。请使用更简洁的HttpStatus.OK.value()代码>使用更简洁和简短的HttpStatus.OK.value()代码>
int statusCode = result.getStatusCode().value();