使用httpclient下载文件

  1. /**  
  2.      * 保存指定URL的源文件到指定路径下  
  3.      *   
  4.      * @param srcUrl 要下载文件的绝对路径url  
  5.      * @param filePath 文件要保存的路径  
  6.      */  
  7.     public static synchronized void downloadFileByUrl(String srcUrl,String filePath) {   
  8.            
  9.         System.out.print("下载"+srcUrl);   
  10.         HttpClient httpclient = new DefaultHttpClient();   
  11.         HttpGet httpget = new HttpGet(srcUrl);   
  12.         HttpResponse response;   
  13.         FileOutputStream out = null;   
  14.         try {   
  15.             String[] array = srcUrl.split("\\/");   
  16.             String[] fname = array[array.length-1].split("\\.");   
  17.             String fileName="",extname="";   
  18.             if(fname.length == 2){   
  19.                 fileName = fname[0];   
  20.                 extname = fname[1];   
  21.             }   
  22.             File wdFile = new File(filePath + fileName+"."+extname);   
  23.             //文件已存在   
  24.             if(wdFile.exists()){   
  25.                 fileName += RandomID.GenTradeId();   
  26.                 wdFile = new File(filePath + fileName+"."+extname);   
  27.             }   
  28.             out = new FileOutputStream(wdFile);   
  29.             response = httpclient.execute(httpget);   
  30.             HttpEntity entity = response.getEntity();   
  31.             if (entity != null) {   
  32.                 InputStream instream = entity.getContent();   
  33.                 int l;   
  34.                 byte[] tmp = new byte[2048];   
  35.                 while ((l = instream.read(tmp)) != -1) {   
  36.                     out.write(tmp, 0, l);   
  37.                 }   
  38.             }   
  39.         } catch (ClientProtocolException e) {   
  40.             e.printStackTrace();   
  41.         } catch (IOException e) {   
  42.             e.printStackTrace();   
  43.         }finally{   
  44.             if(out!=null){   
  45.                 try {   
  46.                     out.close();   
  47.                 } catch (IOException e) {   
  48.                     e.printStackTrace();   
  49.                 }   
  50.             }   
  51.         }   
  52.         System.out.println("............. 结束");   
  53.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值