简体   繁体   中英

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

I created a small spring boot project to showcase what you can do.

First a simple service that will give us an error when called:

@RestController
public class Endpoint {

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

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

The error details which you want to extract are similar to this in this example:

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


}

And then another endpoint with a client that calls the failing service. It returns the error details received:

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

For sake of completion:

@SpringBootApplication
public class StackoverflowApplication {

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

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

When navigating to http://localhost:8080/show-error you see this:

{
"errorMessage": "some error message"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM