我正在使用以下代码在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吗?
这是php的标题,它返回PDF
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");
答案 0 :(得分:2)
我会以这种方式改变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()
}
即使遇到异常,也始终会调用。因此,如果出现错误,您将不会泄漏流
我建议你停止使用Http apache客户端,然后开始使用HttpUrlConnection。