这是从一台服务器获取 pdf 并将其作为响应在 servlet 中提供的代码:
GAELogger.logInfo(LOG, "download request. url: " + downloadURLStr);
HTTPResponse fetchResponse = URLFetchServiceFactory.getURLFetchService().fetch(new URL(downloadURLStr));
byte[] pdfContent = fetchResponse.getContent();
Integer totalLength = pdfContent.length;
String fileName = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
GAELogger.logInfo(LOG, "writing. total: " + totalLength.toString());
response.reset();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".pdf\"");
response.setHeader("Content-Length", totalLength.toString());
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(pdfContent);
outputStream.flush();
outputStream.close();
GAELogger.logInfo(LOG, "done.");
以下是提供 pdf 的请求的日志:
download request. url: http://someurl/test.pdf
writing. total: 43497
logInfo: done.
有时响应为空,chrome 会给出如下错误:
虽然有时它会满足请求并下载 pdf。我尝试了多种方法,例如:
String downloadURLStr = outputFiles.get(0).getUrl();
URL downloadURL = new URL(downloadURLStr);
URLConnection connection = downloadURL.openConnection();
InputStream inputStream = downloadURL.openStream();
OutputStream outputStream = response.getOutputStream();
Integer totalLength = connection.getContentLength();
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "inline; filename=\"" + id + ".pdf\"");
response.setHeader("Content-Length", totalLength.toString());
IOUtils.copy(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
这也失败了。知道为什么吗?