【问题标题】:Read Error Message with HttpURLConnection send by Spring使用 Spring 发送的 HttpURLConnection 读取错误消息
【发布时间】:2018-12-19 09:42:20
【问题描述】:

我有一个使用 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.OK,则Custom Message发送成功,客户端可以读取。因此,问题接缝是 Spring Bean (?) 或 HttpConnection 在出现错误状态时替换主体。

【问题讨论】:

  • 你在哪里调用 handleException() ?
  • 如果@Validated失败,它会由Spring自动完成。
  • HttpURLConnection connection中的URL和访问方式是什么?
  • 网址是www.test.de/doMagic,访问方式当然是Post,因为验证成功了。
  • 有什么理由让你更喜欢 HttpURLConnection。如果您也在客户端使用 spring,那么您可以使用 Spring 的 RestTemplate 并配置错误处理程序来处理失败的请求并读取响应正文。

标签: java spring-mvc httpurlconnection


【解决方案1】:

您可以创建一个专门用于返回错误响应的对象。这样,你就可以说任何你想说的。 点赞:ResponseEntity&lt;ResponseStatus&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 2018-10-05
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    相关资源
    最近更新 更多