我目前正在對服務器進行休息呼叫以簽署 pdf 檔案。
我正在發送 pdf(二進制內容)并檢索已簽名 pdf 的二進制內容。當我從 inputStream 獲取二進制內容時:
try (InputStream inputStream = conn.getInputStream()) {
if (inputStream != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String lines;
while ((lines = br.readLine()) != null) {
output = lines;
}
}
}
}
signedPdf.setBinaryContent(output.getBytes());
(signedPdf 是具有 byte[] 屬性的 DTO)但是當我嘗試使用回應 pdf 的內容設定 pdf 的內容時:
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(signedPdf);
pdf.setContent(signedPdf);
并嘗試打開它,它說pdf已損壞且無法修復。
有人遇到過類似的事情嗎?我是否還需要為輸出流設定內容長度?
uj5u.com熱心網友回復:
PDF 是二進制資料。讀取為文本時會破壞 PDF (在 Java 中始終是 Unicode)。這也是一種浪費:作為 char 的位元組會使記憶體使用量增加一倍,并且有兩種轉換:從位元組到字串,反之亦然,使用某種編碼。從 UTF-8 轉換時,甚至可能會引發 UTF-8 格式錯誤。
try (InputStream inputStream = conn.getInputStream()) {
if (inputStream != null) {
byte[] content = inputStream.readAllBytes();
signedPdf.setBinaryContent(content);
}
}
是否使用 aBufferedInputStream取決于例如預期的 PDF 大小。
此外new String(byte[], Charset),String.getBytes(Charset) 使用顯式 Charset (like StandardCharsets.UTF_8) 比默認的 Charset 多載版本更可取。那些使用當前的平臺編碼,因此提供了不可移植的代碼。在其他平臺/計算機上表現不同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444816.html
