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

问题描述 投票:0回答:1

我正在尝试将HttpStatus转换为Java中的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;
    }
}

java spring http-status-codes
1个回答
0
投票

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

并且枚举定义如下:

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(); 
© www.soinside.com 2019 - 2024. All rights reserved.