1

这是从一台服务器获取 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);

这也失败了。知道为什么吗?

4

1 回答 1

0

我已经有一段时间没有在 Google App Engine 上做任何事情了,但是当时(可能是 2 年前)GAE 会关闭线程,如果它们花费的时间太长的话。也许您应该交叉检查 GAE 所做的限制,以及它们是否会导致这种奇怪的行为。然而,这将回答为什么它有时工作,有时不工作。

于 2013-07-05T10:32:56.207 回答