有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当请求中的头{“Accept”:“application/octetstream”}出现错误时,java返回JSON

当从rest Web服务返回一些错误时,我遇到了一些问题

使用头{"Accept":"application/octet-stream"}发出请求 (如果所有过程都顺利,服务将返回一个文档ResponseEntity<InputStreamResource>

当所有过程都顺利进行时,文档可以正常下载,但当出现错误时,代码跳转到@ControllerAdvice并尝试返回JSON错误。当试图返回JSON springs崩溃时,问题来了:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation 

下面是一些代码的示例:

控制器

@RequestMapping(value = "/test", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE })
    public ResponseEntity<CustomError> test() throws Exception {
        throw new Exception();
    }

控制器建议

@ControllerAdvice
public class ExceptionHandlerAdvice {
    private static final Logger logger = LogManager.getLogger(ExceptionHandlerAdvice.class);

    @ExceptionHandler({Exception.class,Throwable.class})
    @ResponseBody
    public ResponseEntity<CustomError> handleUnhandledException(Exception exception) {
        CustomError error = new CustomError(exception.getMessage());
        return new ResponseEntity<CustomError>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

自定义错误:

public class CustomError {

    private String errorDescription;

    public CustomError(String errorDescription) {
        super();
        this.errorDescription = errorDescription;
    }

    public String getErrorDescription() {
        return errorDescription;
    }

    public void setErrorDescription(String errorDescription) {
        this.errorDescription = errorDescription;
    }

}

我还尝试在@controllerAdvice上返回新的标题

@ExceptionHandler({Exception.class,Throwable.class})
  @ResponseBody
  public ResponseEntity<CustomError> handleUnhandledException(Exception exception) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    CustomError error = new CustomError(exception.getMessage());
    return new ResponseEntity<CustomError>(error,headers, HttpStatus.INTERNAL_SERVER_ERROR);
  }

你知道我怎样才能做到这一点,或者在回复时忽略Accept标题吗? 有可能吗

提前谢谢


共 (0) 个答案