Java代理输出流损坏了空字节

时间:2017-09-18 14:00:33

标签: 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的输出缓冲区限制有关。

1 个答案:

答案 0 :(得分:1)

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);

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