从URL读取奇怪的byte []行为

Pat*_*ler 1 java url bytearray http channel

最后,我的最终目标是:

  • 从URL读取(这是什么问题)
  • 将检索到的[PDF]内容保存到数据库中的BLOB字段(已经固定下来)
  • 从BLOB字段中读取并将该内容附加到电子邮件中
  • 所有这些都没有进入文件系统

使用以下方法的目标是获取byte[]可在下游用作电子邮件附件的目标(以避免写入磁盘):

public byte[] retrievePDF() {

         HttpClient httpClient = new HttpClient();

         GetMethod httpGet = new GetMethod("http://website/document.pdf");
         httpClient.executeMethod(httpGet);
         InputStream is = httpGet.getResponseBodyAsStream();

         byte[] byteArray = new byte[(int) httpGet.getResponseContentLength()];

         is.read(byteArray, 0, byteArray.length);

        return byteArray;
}
Run Code Online (Sandbox Code Playgroud)

对于特定PDF,该getResponseContentLength()方法返回101,689作为长度.的奇怪的是,如果设置了一个断点和询问byteArray变量,它具有101689个字节元素,但是,之后字节#3744的阵列的剩余字节是全零(0). 因此,PDF阅读器客户端(如Adobe Reader)无法读取生成的PDF.

为什么会这样?

通过浏览器检索相同的PDF并保存到磁盘,或者使用如下方法(我在回答此StackOverflow帖子后模式化),得到可读的PDF:

public void retrievePDF() {
    FileOutputStream fos = null;
    URL url;
    ReadableByteChannel rbc = null;

    url = new URL("http://website/document.pdf");

    DataSource urlDataSource = new URLDataSource(url);

    /* Open a connection, then set appropriate time-out values */
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(120000);
    conn.setReadTimeout(120000);

    rbc = Channels.newChannel(conn.getInputStream());

    String filePath = "C:\\temp\\";
    String fileName = "testing1234.pdf";
    String tempFileName = filePath + fileName;

    fos = new FileOutputStream(tempFileName);
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.flush();

    /* Clean-up everything */
    fos.close();
    rbc.close();
}
Run Code Online (Sandbox Code Playgroud)

对于这两种方法,在Windows中右键单击>属性...时,生成的PDF的大小为101,689字节.

为什么字节数组基本上会"停止"部分通过?

Joe*_*e K 5

InputStream.read读取最多byteArray.length字节但可能读不到那么多.它返回它读取的字节数.你应该反复调用它来完全读取数据,如下所示:

int bytesRead = 0;
while (true) {
    int n = is.read(byteArray, bytesRead, byteArray.length);
    if (n == -1) break;
    bytesRead += n;
}
Run Code Online (Sandbox Code Playgroud)