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

标签 java spring http-status-codes

我正在使用 RestTemplate 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;
    }
}

最佳答案

或者,

您只需使用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;
}

关于java - 如何在Java中将HttpStatus代码转换为int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59873404/

相关文章:

java - JTable - 排序不适用于格式化数字

java - 编写返回 void 的方法是一种好习惯吗?

http - 为什么 "Not Modified"是重定向 ("3xx") 状态码?

php - Laravel - 返回 json 和 http 状态码

spring - Apache Tapestry 5.3 IoC 与 Spring 4 IoC

asp-classic - 如何在经典 ASP 中使用 HTTP 子状态发送 HTTP 错误代码?

java - Java定时调用方法

java - 读取包含两个整数列的TXT文件并保存到java中的两个数组中

java - Spring 集成: Programmatically send request to outbound gateway

java - 如何显示/处理成功/失败错误消息