如何将Java中的HttpStatus代码转换为int?

How to convert HttpStatus code to int in Java?

我正在使用 RestTemplate postForEntity 方法 POST 到端点。如果 POST 成功,statusCode variable 应将其值更改为 201 的状态代码,但我在 Java 中将 HttpStatus 转换为 int 时遇到困难。我收到错误 Cannot cast from HttpStatus to 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;
    }
}

Spring 框架 returns 具有 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);
        }
    }
}

枚举定义如下:

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"),

   // ...
}

因此您可以获得如下状态int

int statusCode = result.getStatusCode().value(); 

或者,

您只需使用 getStatusCodeValue() 作为捷径。

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