Java 代理输出流因空字节而损坏

标签 java jsp proxy

我们有一个 JSP,它应该从内部 URL 获取 PDF 并将该 PDF 传递给客户端(就像代理)。

下载的结果已损坏。在大约 18'400 字节之后,我们直到最后才得到 00 字节。有趣的是,下载的字节大小完全正确。

binary difference

    // Get the download
    URL url = new URL(url);
    HttpURLConnection req = (HttpURLConnection)url.openConnection();
    req.setDoOutput(true);
    req.setRequestMethod("GET");

    // Get Binary Response
    int contentLength = req.getContentLength();
    byte ba[] = new byte[contentLength];
    req.getInputStream().read(ba);
    ByteArrayInputStream in = new ByteArrayInputStream(ba);

    // Prepare Reponse Headers
    response.setContentType(req.getContentType());
    response.setContentLength(req.getContentLength());
    response.setHeader("Content-Disposition", "attachment; filename=download.pdf");

    // Stream to Response
    OutputStream output = response.getOutputStream();
    //OutputStream output = new FileOutputStream("c:\\temp\\op.pdf");
    int count;
    byte[] buffer = new byte[8192];
    while ((count = in.read(buffer)) > 0) output.write(buffer, 0, count);

    in.close();
    output.close();

    req.disconnect();

更新 1:我不是唯一一个看到 Java 在 4379 字节 ( link ) 时停止流式传输的人。

更新2:如果我在每次写入后执行output.flush,我会得到更多数据14599字节,然后是空值。一定与tomcat的输出缓冲区限制有关。

最佳答案

int contentLength = req.getContentLength();
byte ba[] = new byte[contentLength];
req.getInputStream().read(ba);
ByteArrayInputStream in = new ByteArrayInputStream(ba);

// Prepare Reponse Headers
response.setContentType(req.getContentType());
response.setContentLength(req.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename=download.pdf");

// Stream to Response
OutputStream output = response.getOutputStream();
//OutputStream output = new FileOutputStream("c:\\temp\\op.pdf");
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0) output.write(buffer, 0, count);

这段代码全是废话。您忽略了第一个 read() 的结果,并且还浪费了 ByteArrayInputStream 的时间和空间。您所需要的只是:

int contentLength = req.getContentLength();

// Prepare Reponse Headers
response.setContentType(req.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=download.pdf");

// Stream to Response
InputStream in = req.getInputStream();
OutputStream output = response.getOutputStream();
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0) output.write(buffer, 0, count);

请注意,内容长度已为您设置。

关于Java 代理输出流因空字节而损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46281222/

相关文章:

java - dl4j 不包含文本和模型模块

java - Android 设备按钮和 PhoneGap/Cordova

Java 6 NTLM 代理身份验证和 HTTPS - 有人让它工作吗?

nginx - 用nginx代理相对URL

java - 无法激活 CXF ResponseTimeFeature

java - 获取浏览器滚动高度

java - JSP:构造变量名称

java - 如何在 JSP 中禁用几行 EL 表达式

java - 我的项目使用jsp和mongodb,使用jar文件连接mongodb和java

c# - Windows 服务托管 WCF 服务的 IIS 代理