程序員備忘

          java技術(shù)
          posts - 8, comments - 0, trackbacks - 0, articles - 0

          HttpClient下載附件

          Posted on 2009-07-22 19:59 波波^_^ 閱讀(1187) 評論(0)  編輯  收藏
          使用HttpClient下載文件主要還是文件流的轉(zhuǎn)化的東西比較煩一點。httpclient的東西比較簡單的
          引用

          需要有的Jar;
              * commons-httpclient-3.1.jar
              * commons-logging-1.04.jar
              * commons-codec-1.3.jar


          Java代碼 復(fù)制代碼
          1. public class HttpClientTest {   
          2.        
          3.     private final static String REMOTE_FILE_URL = "http://www.gjt.org/download/time/java/tar/javatar-2.5.tar.gz";   
          4.        
          5.     private final static int BUFFER = 1024;   
          6.   
          7.     public static void main(String[] args) {   
          8.   
          9.        HttpClient client = new HttpClient();   
          10.        GetMethod httpGet = new GetMethod(REMOTE_FILE_URL);   
          11.         try {   
          12.             client.executeMethod(httpGet);   
          13.                
          14.             InputStream in = httpGet.getResponseBodyAsStream();   
          15.               
          16.             FileOutputStream out = new FileOutputStream(new File("E:\\test_jar\\javatar-2.5.tar.gz"));   
          17.               
          18.             byte[] b = new byte[BUFFER];   
          19.             int len = 0;   
          20.             while((len=in.read(b))!= -1){   
          21.                 out.write(b,0,len);   
          22.             }   
          23.             in.close();   
          24.             out.close();   
          25.                
          26.         }catch (HttpException e){   
          27.             e.printStackTrace();   
          28.         } catch (IOException e) {   
          29.             e.printStackTrace();   
          30.         }finally{   
          31.             httpGet.releaseConnection();   
          32.         }   
          33.         System.out.println("download, success!!");   
          34.        }   
          35. }  

          這個文章主要是參考自
          http://www.hr.utah.edu/blog/2006/03/03/file-download-using-jakarta-commons-httpclient/
          使用了緩沖,避免了IO的頻繁讀寫。

          還有一篇http://weifly.javaeye.com/blog/145457
          直接使用byte[]數(shù)組,比較便捷,但是沒有使用緩沖,因為頻繁的讀寫,看下來下載速度很慢。

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 临泉县| 潜江市| 渝北区| 攀枝花市| 铜梁县| 霍州市| 凭祥市| 贵德县| 隆化县| 胶南市| 达孜县| 清苑县| 曲沃县| 乡宁县| 曲周县| 稷山县| 北辰区| 正蓝旗| 海原县| 长宁县| 南丰县| 方山县| 酒泉市| 元阳县| 诏安县| 博客| 河源市| 卢湾区| 溧阳市| 呈贡县| 肥西县| 贞丰县| 昆山市| 平度市| 宁陵县| 徐闻县| 芦山县| 凭祥市| 汝城县| 重庆市| 易门县|