Using Java to implement HTTP file queue download _jsp programming

Source: Internet
Author: User

  Preface

Many users may experience a situation like this: found a good resource on the site, but this resource is divided into a lot of files stored, if you want to save it to the local, only rely on the user click on save to complete, if the resources divided hundreds of or even thousands of thousands, it is a disaster.

When a lot of resources on the Internet are stored in multiple files, it has a certain rule of naming the file, and because of this, we can use the program to complete the full download of this resource.

  1. Basic knowledge

On the Internet, we want to download a resource on the site, we will get a URL (uniform Resource Locator), it is a description of the server resource positioning, the process of downloading is always the following steps:

    • Step 1: The client initiates a connection request a URL
    • Step 2: The server resolves the URL and returns the specified resource to an input stream to the customer
    • Step 3: The client receives the input stream and saves the contents of the stream to the file
   2. The establishment of network connection

Java provides a URL access and a large number of streaming operations of the API, we can easily complete access to resources on the network, the following code snippet completes the resources of a Web site to access:

......
Desturl= "http://www.ebook.com/java/network programming 001.zip";
url = new URL (desturl); Httpurl = (httpurlconnection) url.openconnection ();
Connecting to a specified network resource
Httpurl.connect ();
Get network input stream
bis = new Bufferedinputstream (Httpurl.getinputstream ());
......

   3. Access by proxy

The way to access the extranet through proxy servers in Java is already known as the Secret of the world. Here is no longer described, access to the Java code is as follows:

Setting up a proxy server
System.getproperties (). Put ("Proxyset", "true");
System.getproperties (). Put ("ProxyHost", "10.154.134.110");
System.getproperties (). Put ("ProxyPort", "8080");

   4. The preservation of network resources

In the previous section, we've got the input stream for the specified network resource, so what we're going to do is read the contents of the input stream and save it in the file. Sample code:

......
FOS = new FileOutputStream (fileName);
if (this. DEBUG)
System.out.println ("Getting the content of the link [" + Desturl +] ... \ n Save it as a file ["+ FileName +]");
Save File
while (size = Bis.read (BUF))!=-1)
Fos.write (buf, 0, size); ......


The example code above saves the contents of a network resource to a locally specified file.

  5. Code Listings

Import Java.io.*;import java.net.*;import java.util.*;/** * <p>title: api</p> for Personal development * <p>Description: Store the specified HTTP network resource locally as a file </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;//debugging with private static int buffer_size = 8096;//buffer size private vector vdownload = new vector ();//url list private vector vfilelist = new Vec Tor ()///Download Save file Name List/** * Construction method/Public HttpGet () {}/** * Clear download list/public void Resetlist () {Vdownload    . Clear ();  Vfilelist.clear (); /** * Add Download list item * * @param URL String * @param filename String */public void AddItem (string url, string filen    AME) {vdownload.add (URL);  Vfilelist.add (filename);    /** * Download resource from list/public void Downloadbylist () {String URL = null;        String filename = null; Save resources in list order for (int i = 0; i < vdownload.size (); i++) {URL= (String) vdownload.get (i);      filename = (String) vfilelist.get (i);      try {savetofile (URL, filename);      The catch (IOException err) {if (DEBUG) {System.out.println (resource [+ URL +] Download failed!!!);}    } if (DEBUG) {System.out.println ("Download complete!!!"); /** * Save HTTP resource as File * * @param desturl String * @param fileName String * @throws Exception/Public Voi    D 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;    Create a link URL = new URL (desturl);    Httpurl = (httpurlconnection) url.openconnection ();    Connect the specified resource Httpurl.connect ();    Gets the network input stream bis = new Bufferedinputstream (Httpurl.getinputstream ());    Create a file Fos = new FileOutputStream (fileName); if (this. DEBUG) System.out.println ("Getting the content of the link [" + Desturl +] ... \ n willIt is saved as a file ["+ FileName +]");        Save file while (size = Bis.read (BUF))!=-1) fos.write (buf, 0, size);    Fos.close ();    Bis.close ();  Httpurl.disconnect (); /** * Set Proxy Server * * @param proxy String * @param proxyport string/public void Setproxyserver (string proxy,    String proxyport) {//Set proxy Server System.getproperties (). Put ("Proxyset", "true");    System.getproperties (). Put ("ProxyHost", proxy);  System.getproperties (). Put ("ProxyPort", ProxyPort); /** * Set authentication username and password * * @param uid String * @param pwd string/public void Setauthenticator (string uid, Strin  g pwd) {Authenticator.setdefault (new Myauthenticator (UID, pwd)); /** * Main method (for testing) * * @param argv string[]/public static void Main (String argv[]) {httpget oinstance = NE W HttpGet (); try {//Add download list (where users can write their own code to increase the download list) Oinstance.additem ("http://www.ebook.com/java/Network Programming 001.zip", "./ Network programming 1.zip "); Oinstance.additem (" http://www.ebook.com/java/Network Programming 002.zip ","./network Programming 2.zip "); oinstance. AddItem ("http://www.ebook.com/java/Network Programming 003.zip", "./network Programming 3.zip"); Oinstance.additem ("http://www.ebook.com/java/ Network programming 004.zip ","./network Programming 4.zip "); Oinstance.additem (" http://www.ebook.com/java/Network Programming 005.zip ","./network Programming 5.zip "); o Instance.additem ("http://www.ebook.com/java/Network Programming 006.zip", "./network Programming 6.zip"); Oinstance.additem ("http://    www.ebook.com/java/Network Programming 007.zip ","./network Programming 7.zip ");//start downloading oinstance.downloadbylist ();    catch (Exception err) {System.out.println (Err.getmessage ()); }  }}

   Download Source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.