`
忧里修斯
  • 浏览: 427103 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

使用httpclient下载文件

 
阅读更多
/**
	 * 保存指定URL的源文件到指定路径下
	 * 
	 * @param srcUrl 要下载文件的绝对路径url
	 * @param filePath 文件要保存的路径
	 */
	public static synchronized void downloadFileByUrl(String srcUrl,String filePath) {
		
		System.out.print("下载"+srcUrl);
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(srcUrl);
		HttpResponse response;
		FileOutputStream out = null;
		try {
			String[] array = srcUrl.split("\\/");
			String[] fname = array[array.length-1].split("\\.");
			String fileName="",extname="";
			if(fname.length == 2){
				fileName = fname[0];
				extname = fname[1];
			}
			File wdFile = new File(filePath + fileName+"."+extname);
			//文件已存在
			if(wdFile.exists()){
				fileName += RandomID.GenTradeId();
				wdFile = new File(filePath + fileName+"."+extname);
			}
			out = new FileOutputStream(wdFile);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
			    InputStream instream = entity.getContent();
			    int l;
			    byte[] tmp = new byte[2048];
			    while ((l = instream.read(tmp)) != -1) {
			    	out.write(tmp, 0, l);
			    }
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("............. 结束");
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics