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

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

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 引导项目来展示您可以做什么。

首先是一个简单的服务,调用时会报错:

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


}

然后是另一个端点,其客户端调用了失败的服务。它 returns 收到错误详细信息:

@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 WhosebugApplication {

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

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

导航到 http://localhost:8080/show-error 时,您会看到:

{
"errorMessage": "some error message"
}