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 download process 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 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/网络编程001.zip";
url = new URL(destUrl); httpUrl = (HttpURLConnection) url.openConnection();
//连接指定的网络资源
httpUrl.connect();
//获取网络输入流
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:
//设置代理服务器
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("正在获取链接[" + destUrl + "]的内容...\n将其保存为文件[" + fileName +"]");
//保存文件
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.