【发布时间】:2015-04-17 17:29:43
【问题描述】:
我正在从我的服务器下载 PDF。
服务器向我发送HttpResponse 和文件正文的InputStream。
我可以将其写入文件,但是当我尝试使用 PDF 阅读器阅读时,它告诉我文件可能已损坏。
我还注意到直接从网络服务下载的 PDF 的大小是通过我的应用程序下载的 PDF 大小的两倍。
我用来下载和编写PDF文件的代码是这样的:
String fileName = //FILENAME + ".pdf";
fileName = fileName.replaceAll("/", "_");
String extPath = Environment.getExternalStorageDirectory().toString();
String folderName = //FOLDERNAME;
try {
File folder = new File(extPath, folderName);
folder.mkdir();
File pdfFile = new File(folder, fileName);
pdfFile.createNewFile();
URL url = new URL(downloadURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
byte[] buffer = new byte[MEGABYTE];
int bufferLength;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
//otherStuff
我哪里出错了?
我还注意到HttpResponse 的Headers 内部包含Content-type:text/html。它应该类似于text/pdf?
【问题讨论】:
-
你能从应用程序外部打开文件吗(意味着从文件资源管理器)?
-
不。即使在应用程序之外打开也会告诉我它已损坏。
标签: android pdf httpresponse