首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >被空字节损坏的Java代理输出流

被空字节损坏的Java代理输出流
EN

Stack Overflow用户
提问于 2017-09-18 14:00:32
回答 1查看 213关注 0票数 0

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

由此产生的下载已损坏。在大约18'400字节之后,我们只能得到00字节直到结尾。有趣的是,下载的大小(以字节为单位)是完全正确的。

代码语言:javascript
复制
    // 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字节(链接)停止流的人。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-20 12:18:44

代码语言:javascript
复制
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的时间和空间。你只需要这样:

代码语言:javascript
复制
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);

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46281222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档