java - org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity

标签 java spring spring-boot spring-rest

I am consuming API which has to type of response success response 200 and Bad response 400 both of them has parameters inside their response body but the problem is am not able to get the bad response parameters it throws this exception

public ResponseEntity<String> balanceInquiry(BalanceInquiryRequestDto balanceInquiryRequestDto) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("API-KEY", "5d6f54d4");
        HttpEntity<BalanceInquiryRequestDto> request = new HttpEntity<BalanceInquiryRequestDto>(balanceInquiryRequestDto , httpHeaders);

        ResponseEntity<String> postForEntity = 
                restTemplate.postForEntity(uri , request, String.class);
        return postForEntity;

}

it is working good when the response is ok 200

最佳答案

我创建了一个小型 Spring Boot 项目来展示您可以做什么。

首先是一个简单的服务,调用时会给我们一个错误:

@RestController
public class Endpoint {

    @GetMapping("/error")
    public ResponseEntity createError() {

        ErrorDetails errorDetails = new ErrorDetails("some error message");
        return ResponseEntity.status(400).body(errorDetails);;
    }
}

您要提取的错误详细信息与此示例中的类似:

@AllArgsConstructor
@Getter
@Setter
@ToString
@EqualsAndHashCode
public class ErrorDetails {
    private String errorMessage;


}

然后另一个端点的客户端调用失败的服务。它返回收到的错误详细信息:

@RestController
public class ClientDemo {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/show-error")
    public String createError() {

        try{
            return restTemplate.getForEntity("http://localhost:8080/error", String.class).getBody();
        } catch(HttpClientErrorException | HttpServerErrorException ex) {
            return ex.getResponseBodyAsString();
        }
    }
}

为了完成:

@SpringBootApplication
public class StackoverflowApplication {

    public static void main(String[] args) {
        SpringApplication.run(StackoverflowApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

导航至 http://localhost:8080/show-error 时你会看到这个:

{
"errorMessage": "some error message"
}

关于java - org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52743530/

相关文章:

Javafx 将 ActionListener 添加到按钮

java - 如何使用mockito模拟Spring Controller 测试中的字段?

java - Spring 中对版本化实体的 ETag 支持

json - 哪个 bean 在 Spring Boot 中将对象转换为 Json?

java - 将 Java 8 lambda 谓词与逻辑运算符相结合

java - SQLite - 选择不同日期的第一条记录

java - 有什么方法可以将自定义字段发送到 mongo 存储库进行搜索吗?

java - 用于两个数据库连接的通用 spring 数据存储库

java - 由 : org. hibernate.PropertyNotFoundException 引起:无法在类上找到字段名称

hibernate - Spring boot + hibernate - 实体未映射 + 最佳配置方式