用Java實現HTTP檔案隊列下載

來源:互聯網
上載者:User

  序言

  許多使用者可能會遇到這樣的情況:在網站上發現一個很好的資源,但是這個資源是分成了很多個檔案存放的,如果想把它儲存到本地,只有靠使用者點擊另存來完成儲存,如果資源分了幾百甚至上千上萬,那簡直是個災難。

  在Internet上很多的資源分成多個檔案存放時,它的檔案命名是有一定的規則的;正因如此,我們就可以用程式來完成這個資源的完全下載。

  1. 基礎知識

  在Internet上,我們要下載網站上的某個資源,我們會獲得一個URL(Uniform Resource Locator),它是一個伺服器資源定位的描述,下載的過程總是如下步驟:

  • 步驟1:用戶端發起串連請求一個URL
  • 步驟2:伺服器解析URL,並將指定的資源返回一個輸入資料流給客戶
  • 步驟3:用戶端接收輸入資料流,將流中的內容存到檔案

  2. 網路連接的建立

  Java提供了對URL訪問和大量的流操作的的API,我們可以很容易的完成對網路上資源的存取,下面的程式碼片段就完成了對一個網站的資源進行訪問:

......
destUrl="http://www.ebook.com/java/網路編程001.zip";
url = new URL(destUrl); httpUrl = (HttpURLConnection) url.openConnection();
//串連指定的網路資源
httpUrl.connect();
//擷取網路輸入資料流
bis = new BufferedInputStream(httpUrl.getInputStream());
......

  3. 代理的訪問

  Java 中通過Proxy 伺服器訪問外網的方法已經是世人皆知的秘密了。這裡就不再多描述了,訪問的Java代碼如下:

//設定Proxy 伺服器
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "10.154.134.110");
System.getProperties().put("proxyPort", "8080");

  4. 網路資源的儲存

  在上節中,我們已經擷取了指定網路資源的輸入資料流,接下來我們要完成的就是讀取輸入資料流中的所以內容,並將其儲存在檔案中。 範例程式碼:

......
fos = new FileOutputStream(fileName);
if (this.DEBUG)
 System.out.println("正在擷取連結[" + destUrl + "]的內容...\n將其儲存為檔案[" + fileName +"]");
//儲存檔案
while ( (size = bis.read(buf)) != -1)
 fos.write(buf, 0, size); ......

  上面的範例程式碼就將網路資源的內容儲存到了本地指定的檔案中。

  5. 代碼清單


import java.io.*;import java.net.*;import java.util.*;/** * <p>Title: 個人開發的API</p> * <p>Description: 將指定的HTTP網路資源在本地以檔案形式存放</p> * <p>Copyright: Copyright (c) 2004</p> * <p>Company: NewSky</p> * @author MagicLiao * @version 1.0 */public class HttpGet {  public final static boolean DEBUG = true;//調試用  private static int BUFFER_SIZE = 8096;//緩衝區大小  private Vector vDownLoad = new Vector();//URL列表  private Vector vFileList = new Vector();//下載後的儲存檔案名稱列表  /**   * 構造方法   */  public HttpGet() {  }  /**   * 清除下載列表   */  public void resetList() {    vDownLoad.clear();    vFileList.clear();  }  /**   * 增加下載清單項目   *   * @param url String   * @param filename String   */  public void addItem(String url, String filename) {    vDownLoad.add(url);    vFileList.add(filename);  }  /**   * 根據列表下載資源   */  public void downLoadByList() {    String url = null;    String filename = null;        //按列表順序儲存資源    for (int i = 0; i < vDownLoad.size(); i++) {      url = (String) vDownLoad.get(i);      filename = (String) vFileList.get(i);      try {        saveToFile(url, filename);      }      catch (IOException err) {        if (DEBUG) {          System.out.println("資源[" + url + "]下載失敗!!!");        }      }    }    if (DEBUG) {      System.out.println("下載完成!!!");    }  }  /**   * 將HTTP資源另存新檔檔案   *   * @param destUrl String   * @param fileName String   * @throws Exception   */  public void saveToFile(String destUrl, String fileName) throws IOException {    FileOutputStream fos = null;    BufferedInputStream bis = null;    HttpURLConnection httpUrl = null;    URL url = null;    byte[] buf = new byte[BUFFER_SIZE];    int size = 0;        //建立連結    url = new URL(destUrl);    httpUrl = (HttpURLConnection) url.openConnection();    //串連指定的資源    httpUrl.connect();    //擷取網路輸入資料流    bis = new BufferedInputStream(httpUrl.getInputStream());    //建立檔案    fos = new FileOutputStream(fileName);    if (this.DEBUG) System.out.println("正在擷取連結[" + destUrl + "]的內容...\n將其儲存為檔案[" + fileName + "]");    //儲存檔案    while ( (size = bis.read(buf)) != -1)       fos.write(buf, 0, size);        fos.close();    bis.close();    httpUrl.disconnect();  }  /**   * 設定Proxy 伺服器   *   * @param proxy String   * @param proxyPort String   */  public void setProxyServer(String proxy, String proxyPort) {    //設定Proxy 伺服器    System.getProperties().put("proxySet", "true");    System.getProperties().put("proxyHost", proxy);    System.getProperties().put("proxyPort", proxyPort);  }  /**   * 設定認證使用者名稱與密碼   *   * @param uid String   * @param pwd String   */  public void setAuthenticator(String uid, String pwd) {    Authenticator.setDefault(new MyAuthenticator(uid, pwd));  }  /**   * 主方法(用於測試)   *   * @param argv String[]   */  public static void main(String argv[]) {    HttpGet oInstance = new HttpGet();try {//增加下載列表(此處使用者可以寫入自己代碼來增加下載列表)oInstance.addItem("http://www.ebook.com/java/網路編程001.zip","./網路編程1.zip");oInstance.addItem("http://www.ebook.com/java/網路編程002.zip","./網路編程2.zip");oInstance.addItem("http://www.ebook.com/java/網路編程003.zip","./網路編程3.zip");oInstance.addItem("http://www.ebook.com/java/網路編程004.zip","./網路編程4.zip");oInstance.addItem("http://www.ebook.com/java/網路編程005.zip","./網路編程5.zip");oInstance.addItem("http://www.ebook.com/java/網路編程006.zip","./網路編程6.zip");oInstance.addItem("http://www.ebook.com/java/網路編程007.zip","./網路編程7.zip");//開始下載oInstance.downLoadByList();    }    catch (Exception err) {      System.out.println(err.getMessage());    }  }}

  下載原始碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.