【发布时间】:2021-07-05 05:07:24
【问题描述】:
考虑下面的代码。这里,当响应返回的状态码为200时,代码执行完美。
但如果我尝试返回状态码 400,则会在指定行捕获异常。
*错误响应:内部服务器错误:“http://localhost:8090/get-data”的 POST 请求中的 getResponse I/O 错误:服务器返回的 HTTP 响应代码:400 对于 URL:http://localhost:8090/get-data;嵌套异常是 java.io.IOException:服务器返回 HTTP 响应代码:400 用于 URL:http://localhost:8090/get-data
连接:关闭,内容长度:485,内容类型:application/json,日期:2021 年 4 月 8 日星期四 20:25:47 GMT*
为什么返回状态 400 时会抛出异常?
@RestController
Class ABC{
@Autowired
RestTemplate template;
@PostMapping("....")
ResponseEntity<Object> getResponse(){
ResponseEntity<String> response
try{
HttpEntity<Object> body=new HttpEntity(obj,header); // data obj & httpheader
response=template.postForEntity("http://localhost:8090/get-
data",body,String.class);
}catch(HttpStatusCodeException ex){
throw....
}catch(Exception ex){
throw Internal Server Error..... //Exception is thrown here
}
if(response.getStatusCodeValue()==200){
...
}
...
}
}
@RestController
Class XYZ{
@PostMapping("/get-data")
ResponseEntity<Object> getTheStatus(@RequestHeader HttpHeaders headers ,@ResponseBody MyData data){
return new ResponseEntity<>("",HttpStatus.BAD_REQUEST);
}
}
【问题讨论】:
标签: java spring-boot