【发布时间】:2012-09-24 22:16:03
【问题描述】:
最后,我的终极目标是:
- 从 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;
}
对于特定的 PDF,getResponseContentLength() 方法返回 101,689 作为长度。 奇怪部分是如果我设置一个断点并询问byteArray变量,它有101,689个字节元素,但是,在字节#3744之后,数组的剩余字节全为零(@ 987654326@)。 PDF 阅读器客户端(如 Adobe Reader)无法读取生成的 PDF。
为什么会这样?
通过浏览器检索相同的 PDF 并将其保存到磁盘,或使用类似以下的方法(我以 answer to this StackOverflow post 为模板),生成可读的 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();
}
对于这两种方法,在 Windows 中执行 右键单击 > 属性... 时,生成的 PDF 的大小为 101,689 字节。
为什么字节数组会中途“停止”?
【问题讨论】:
标签: java http url bytearray channel