![](/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.