我正在使用此代码在 android 中下载和保存 PDF 文件:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
HttpResponse response;
FileOutputStream fileOutputStream;
/*We will write the file to external storage.
If External Storage is not available, then we use internal storage
*/
ApplicationLevel appLevel=(ApplicationLevel) context;
if(appLevel.isExternalStorageReadable() && appLevel.isExternalStorageWritable())
file=new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),"example.pdf");
else
file=new File(context.getFilesDir(),"example.pdf");
String path;
android.util.Log.v(TAG,"strings[0] : "+strings[0]);
try {
URI uri = new URI("www.getpdf.com");
request.setURI(uri);
response = httpclient.execute(request);
InputStream in = response.getEntity().getContent();
String inputLine;
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
android.util.Log.v(TAG, "starting content reading..." );
while ((in.read(buf)) > -1) {
fileOutputStream.write(buf);
}
android.util.Log.v(TAG,"Content Reading done.");
in.close();
fileOutputStream.close();
} catch (URISyntaxException e) {
android.util.Log.v(TAG, e.toString());
return false;
} catch (IOException e) {
android.util.Log.v(TAG, e.toString());
return false;
}
我认为下载的 pdf 不合适。当我尝试通过手机上的“AdobeAcrobat”打开 pdf 时,它有时可以工作,有时无法呈现 pdf。
我是否正确下载了 pdf 文件?
这是返回 PDF 的 php header
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".filesize($attachment_location));
header("Content-Disposition: inline; filename=$_GET[get].pdf");
最佳答案
我会这样改变while循环
int read = 0;
while ((read = in.read(buf)) > -1) {
fileOutputStream.write(buf, 0, read);
}
你不能确定在每次迭代时都准确读取 1024
字节,你的缓冲区大小,我会添加一个 finally
子句来关闭流:
try {
} catch(..) {
} finally {
// here call fileOutputStream.close()
// and in.close()
}
finally 总是被调用,即使在异常情况下也是如此。所以你不会在错误的情况下泄漏流
我建议您停止使用 Http apache 客户端,而开始使用 HttpUrlConnection。
关于php - 这是在 android 中下载 PDF 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31043348/