简体   繁体   English

具有ResponseEntity和pdf的HttpStatus

[英]HttpStatus with ResponseEntity and pdf

I have a spring mvc controller which produces an "application/pdf" to download a generated pdf. 我有一个弹簧mvc控制器,该控制器产生一个“应用程序/ pdf”来下载生成的pdf。 I want to return always the pdf and also return different HTTP codes depending on certain conditions. 我想始终返回pdf,并根据某些条件还返回不同的HTTP代码。

I tried to return a ResponseEntity<> object but always response is 200 with the PDF (always the pdf is generated, but I need different status responses). 我试图返回ResponseEntity <>对象,但PDF的响应始终为200(总是生成pdf,但我需要不同的状态响应)。

@RequestMapping(value = "/obtain/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
@ResponseBody
public ResponseEntity<?> getPdfFile(HttpServletResponse response,HttpServletRequest request) throws IOException{

    response.setHeader("Content-disposition", "inline; filename=\"" +"file.pdf" +"\"");
    String error = getPDF(response, request);
    logger.debug("PDF error : " + StringUtils.defaultIfEmpty(error,"null") );
    return new ResponseEntity<>("",HttpStatus.INTERNAL_SERVER_ERROR);
}

Note : Inside getPDF method, is just the code which generates the pdf and write it to the response.getOutputStream() . 注意:在getPDF方法中,仅是生成pdf并将其写入response.getOutputStream()的代码

The idea behing is that I want to return ALWAYS the pdf in the outputstream, but different result codes (200, 500, etc). 我的想法是,我想始终在输出流中返回pdf,但是返回不同的结果代码(200、500等)。 Event when I return 500, I want to return a PDF. 返回500时的事件,我想返回PDF。 Is it possible? 可能吗?

Any help will be appreciated. 任何帮助将不胜感激。

I am not 100% sure about this, but I think the method is returning whatever is in the HttpServletResponse , rather that the object you are returning. 我对此不太确定,但是我认为该方法返回的是HttpServletResponse ,而不是您返回的对象。

I think you should experiment with HttpServletResponse.getWriter().write(responseEntity.getBody()) and HttpServletResponse.setHttpStatus(responseEntity.getHttpStatus()) , or just the equivalent hard-coded values... 我认为您应该尝试使用HttpServletResponse.getWriter().write(responseEntity.getBody())HttpServletResponse.setHttpStatus(responseEntity.getHttpStatus())或仅使用等效的硬编码值进行实验...

Also, are you seeing the errors and the 200 status alongside each other? 另外,您是否同时看到错误和200状态? If so, try parameterizing the entity as a String - whatever Throwable you put in there should still work fine. 如果是这样,请尝试将实体参数化为字符串-放置在其中的任何Throwable应该仍然可以正常工作。

Please let me know if you try that and it doesn't work so I can edit or remove this answer - I haven't actually tried this yet, but interested to find out why that code is not working. 如果您尝试这样做,请告诉我,但该方法不起作用,因此我可以编辑或删除此答案-我实际上尚未尝试过此方法,但是有兴趣了解为什么该代码不起作用。

The ideal way is to set response status ( response.setStatus(statusCode) ) in getPDF() which return the String message which you can show to the client. 理想的方法是在getPDF()中设置响应状态( response.setStatus(statusCode) ) ,该状态返回可以显示给客户端的String消息 Now to you can get the status using response.getStatus() and can give a response to the client. 现在,您可以使用response.getStatus()获取状态,并可以将响应提供给客户端。 You told that you want to download PDF file no matter which status code is there, below code does the same. 您告诉您要下载PDF文件,而不管其中的状态码是什么,下面的代码都一样。 But in my opinion when there some conditions which are not satisfying then you should not return PDF file. 但是我认为, 当某些条件不满足时,您不应退还PDF文件。

As I don't know for which condition you want Status 500, I have created one sample which randomly generates the number and according to the condition it sets the response code. 由于我不知道要针对哪个条件使用状态500,因此我创建了一个样本,该样本随机生成数字,并根据条件设置响应代码。

@RequestMapping(value = "/obtain/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<?> getPdfFile(HttpServletResponse response,HttpServletRequest request) throws IOException{

        response.setHeader("Content-disposition", "inline; filename=\"" +"file.pdf" +"\"");
        String message = getPDF(response, request);
        System.out.println("statusCodeString: "+message + "Status: "+response.getStatus());

        return new ResponseEntity<>(message,(response.getStatus() == 500 ? HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.OK));
    }

    private String getPDF(HttpServletResponse response, HttpServletRequest request) {
        int min = 0;
        int max = 10;
        int num = (int) min + (int)(Math.random() * ((max - min) + 1));
        System.out.println("Number: "+num);
        if(num<=5)
        {
            response.setStatus(200);
            return "200 <message for 200>";
        }
        else
        {
            response.setStatus(500);
            return "500 <message for 500>";
        }       
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 引导:如果 DataSource 为 DOWN,则在 ResponseEntity 中返回 503 HttpStatus 的最佳方式 - Spring Boot: Best way to return 503 HttpStatus in ResponseEntity if the DataSource is DOWN 创建PDF并在ResponseEntity中返回 - Create PDF and return it in ResponseEntity 与responseEntity问题。 即使ResponseEntity.HttpStatus为201,MockMvc.Perform()也会提供200个状态代码 - Issue with responseEntity . MockMvc.Perform() gives 200 status code even if the ResponseEntity.HttpStatus is 201 抛出 BadRequestException(ResponseEntity) vs Catch 错误,返回 ResponseEntity(HTTPStatus.BadRequest) ReST API - Throw BadRequestException(ResponseEntity) vs Catch Error, return ResponseEntity(HTTPStatus.BadRequest) ReST API 即使使用HttpStatus.BAD_REQUEST返回ResponseEntity,也要在API响应中获取HTTP响应代码200 - Getting HTTP response code 200 in API response even after returning ResponseEntity with HttpStatus.BAD_REQUEST 在新的浏览器选项卡中打开 ResponseEntity PDF - Open ResponseEntity PDF in new browser tab 如何在 Spring 引导中将 pdf 数据从 HttpResponse 传递到 ResponseEntity - How to pass pdf data from HttpResponse to ResponseEntity in Spring boot 响应实体 <?> 和ResponseEntity不一样吗? - ResponseEntity<?> and ResponseEntity are not the same? Spring 响应实体 - Spring ResponseEntity 为 HttpClientErrorException 设置 Httpstatus 499 - Setting Httpstatus 499 for HttpClientErrorException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM