[英]Downloading a PDF file
In my application, the user needs to download PDF file from an url and store it on sdcard. 在我的应用程序中,用户需要从URL下载PDF文件并将其存储在sdcard上。 But the catch here is I can only use DefaultHttpClient to access the url. 但是这里的问题是我只能使用DefaultHttpClient来访问URL。 I found couple of solutions but none used DefaultHttpClient. 我找到了几种解决方案,但都没有使用DefaultHttpClient。 After downloading the PDF, I would also likie to view the PDF in my application. 下载PDF之后,我也希望在我的应用程序中查看PDF。
//use this method to download the pdf file //使用此方法下载pdf文件
public void downloadPdfContent(String urlToDownload){
try {
String fileName="xyz";
String fileExtension=".pdf";
// download pdf file.
URL url = new URL(urlToDownload);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName+fileExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
} catch (Exception e) {
e.printStackTrace();
}
}
// for viewing the pdf use this method //要查看pdf,请使用此方法
private void onPdfClick()
{
// String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");
startActivity(intent);
}
请参阅http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html ,以使用DefaultHttpClient从网址中检索数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.