【发布时间】:2015-09-11 15:31:23
【问题描述】:
我正在使用此代码在 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($_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");
【问题讨论】:
-
参考这个stackoverflow.com/questions/9551058/…HttpURLConnection是最好的选择。其简单的 API 和小尺寸使其非常适合 Android。透明压缩和响应缓存可减少网络使用、提高速度并节省电池。