2011-12-05 166 views
1

在我的应用程序中,用户需要从网址下载PDF文件并将其存储在SD卡上。 但是这里的catch是我只能使用DefaultHttpClient来访问url。 我找到了几个解决方案,但没有使用DefaultHttpClient。 下载PDF后,我也想在我的应用程序中查看PDF。正在下载PDF文件

回答

4

从URL retreiving数据//使用这个方法来下载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(); 

      } 
    } 

//用于查看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); 
    } 
+0

正如我在我的问题中提到的,我想使用DefaulthttpClient。 在你的答案中,你已经使用HttpURLConnection – Gaurav

+0

你可以改变它为DefaulthttpClient,最新的问题。 –

+1

非常感谢。对不起,我花了时间。其实问题是,我的网址有一些重定向,所以我已经处理,以及..但你的代码效果不错:) – Gaurav

1

如果您必须打开PDF文件,必须在您的设备上安装pdf阅读器。否则它将显示空白屏幕。 也here是很好的例子从服务器下载pdf查看其内容