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

时间:2018-10-10 15:16:25

标签: java spring spring-boot spring-rest

  

我正在使用的API的响应类型必须为成功响应200和错误响应400,它们都在响应主体内部具有参数,但问题是无法获取错误响应参数,因此会抛出此异常

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;

}
  

200响应正常时工作正常

1 个答案:

答案 0 :(得分:2)

我创建了一个小的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"
}