首页 > 解决方案 > 使用 Spring 发送的 HttpURLConnection 读取错误消息

问题描述

我有一个使用 Json 请求参数的 Spring-MVC 控制器。如果此参数的验证失败,我想发送一条自定义错误消息。

因此,我将此 ExceptionHandler 添加到我的控制器中,该控制器可以正常工作(在调试期间达到断点)。

控制器类:

@ExceptionHandler
@ResponseBody
public ResponseEntity<String> handleException(MethodArgumentNotValidException exception) {
     return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Custom Message");
}

@RequestMapping(value = "/doMagic", method = RequestMethod.POST, 
                consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntity<String> getAllStudies(@Validated @RequestBody JsonDTO params)
{
    ...
}

在客户端站点上,我使用 Java utils 中的 HttpURLConnection。

客户端类:

private static String getErrorString(HttpURLConnection connection) throws IOException{
    if(connection.getErrorStream() != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        return response.toString();
    } else {
        return null;
    }

问题是,错误信息总是

Server returned HTTP response code: 400 for URL: www.test.de/doMagic

我如何收到我的Custom Message

编辑:

如果我将 ExceptionHandler 的返回状态更改为HttpStatus.OKCustom Message则发送成功并且可以被客户端读取。因此,问题接缝是 Spring Bean (?) 或 HttpConnection 在出现错误状态时替换主体。

标签: javaspring-mvchttpurlconnection

解决方案


您可以创建一个专门用于返回错误响应的对象。这样,你就可以说任何你想说的。喜欢:ResponseEntity<ResponseStatus>


推荐阅读