httpclient 로 파일 다운로드

1773 단어 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(".............   ");
	}

좋은 웹페이지 즐겨찾기