在请求中提供pdf会导致空响应

时间:2013-07-05 10:27:53

标签: java google-app-engine

以下是从一个服务器获取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会出现如下错误:

enter image description here

虽然有时它确实服务于请求并且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);

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

1 个答案:

答案 0 :(得分:0)

我在谷歌应用引擎上没有做任何事情已经有一段时间了,但当时(也许是2年前)GAE关闭线程,如果他们花了太长时间。也许你应该交叉检查GAE的限制,如果它们导致那种奇怪的行为。然而,这可以解释为什么它有时会起作用,有时却不起作用。