【问题标题】:Custom proxy copying PDF自定义代理复制 PDF
【发布时间】:2013-02-22 17:08:58
【问题描述】:

我正在为我们的主应用程序编写一个自定义代理作为 Web 服务客户端,该应用程序使用 REST Web 服务。出于安全原因,我尝试使用客户端的 servlet 作为代理从服务器端检索 PDF,然后通过客户端应用程序在应用程序 Web 浏览器中显示它。

作为这个的核心,我有这段代码:

  protected void copy(HttpResponse fromResponse, HttpServletResponse toResponse)
      throws IOException{
    HttpEntity entity = fromResponse.getEntity();
    for(Header header:fromResponse.getAllHeaders()){
      toResponse.setHeader(header.getName(), header.getValue());
    }

    BufferedInputStream inputStream = new BufferedInputStream(entity.getContent());
    BufferedOutputStream outputStream = new BufferedOutputStream(toResponse.getOutputStream());

int oneByte;
int byteCount = 0;
while((oneByte = inputStream.read()) >= 0){
  outputStream.write(oneByte);
  ++byteCount;
}

log.debug("Bytes copied:" + byteCount);

它应该将返回的输出流中的 PDF 复制到当前的输出流中,然后返回它。

但是,当我运行它时,我从 Adob​​e Reader 收到一条错误消息,指出文件已损坏且无法修复。当我直接运行 URL 时,文件很好,所以它必须是交接中的东西。 byteCount 等于 PDF 文件大小。

有人知道问题出在哪里吗?

【问题讨论】:

    标签: java jakarta-ee pdf servlets


    【解决方案1】:

    通过做

    while((inputStream.read(buffer)) >= 0){
      outputStream.write(buffer);
    }
    

    您将始终写入缓冲区的完整长度,而不管其有效内容长度如何,因为 write 只能查看缓冲区的大小来确定要写入的内容。

    int count;
    while(((count = inputStream.read(buffer))) >= 0){
      outputStream.write(buffer,0,count);
    }
    

    应该解决这个问题。

    【讨论】:

    • 有人向我指出了同样的事情。我已经修改了代码,但仍然遇到同样的问题。
    【解决方案2】:

    我在写入后关闭了 outputStream,它工作正常。

    我不认为你应该这样做?

    【讨论】:

    • outputStream.flush() 应该够用了
    • outputStream 是一个 BufferedOutputStream,因此您显然最终需要通过关闭来显式或隐式地刷新它的缓冲区。
    猜你喜欢
    • 2015-07-25
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多