![](/img/trans.png)
[英]Server returned HTTP response code: 400 for URL : java.io.IOException
[英]Spring Boot: returned HTTP response code 400, nested exception is java.io.IOException
考虑下面的代码。这里,当响应返回的状态码是 200 时,代码执行完美。
但如果我尝试返回状态码 400,则会在指定行捕获异常。
* Error Response : Internal Server Error in: getResponse I/O error on POST request for "http://localhost:8090/get-data": Server returned HTTP response code: 400 for URL: http://localhost:8090/获取数据; nested exception is java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8090/get-data
连接:关闭,内容长度:485,内容类型:应用程序/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);
}
}
在 HTTP 上下文响应状态 200 表示成功响应。 状态 4xx 和 5xx 代表一些问题。 问题可能与请求、连接、服务器或其他来源有关。 一些 HTTP 客户端实现如 RestTemplate 将在不成功状态代码的情况下抛出异常,因为不成功响应状态表示执行失败。
如果要避免异常,可以添加错误处理程序。
public class RestTemplateResponseErrorHandler
implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse httpResponse) throws IOException {}
}
RestTemplate restTemplate = restTemplateBuilder
.errorHandler(new RestTemplateResponseErrorHandler())
.build();
template.postForEntity("http://localhost:8090/get-data", body, String.class);
这是因为传递了 HttpStatus.BAD_REQUEST
恕我直言,像这样返回 4xx 状态不是最好的方法,请改用@ControllerAdvice
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.