gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:14:35 25 4
gpt4 key购买 nike

我们有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com