依赖包:
1 <dependency>
2 <groupId>org.apache.commons</groupId>
3 <artifactId>commons-lang3</artifactId>
4 <version>3.3.2</version>
5 </dependency>
6 <dependency>
7 <groupId>org.apache.httpcomponents</groupId>
8 <artifactId>httpcore</artifactId>
9 <version>4.3.2</version>
10 </dependency>
11 <dependency>
12 <groupId>org.apache.httpcomponents</groupId>
13 <artifactId>httpclient</artifactId>
14 <version>4.3.5</version>
15 </dependency>
源代码:
1 package demo.httpclient.test;
2
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.net.MalformedURLException;
8
9 import org.apache.commons.lang3.StringUtils;
10 import org.apache.http.client.methods.CloseableHttpResponse;
11 import org.apache.http.client.methods.HttpGet;
12 import org.apache.http.impl.client.CloseableHttpClient;
13 import org.apache.http.impl.client.HttpClients;
14
15 public class Download {
16
17 public static void main(String[] args) throws MalformedURLException {
18
19 // 启始编号
20 int start = 96;
21 // 结束编号
22 int end = 97;
23 // url中去除最后的文件名的部分
24 String prefix = "http://s5.hxen.com/m2/tingli/nce/";
25 // 有规则的文件名称
26 String pattern = "2-{x}.mp3";
27 // pattern中,x的位置。是否需要补充空格
28 int bitNum = 2;
29
30 String fileName = "";
31 String urlStr = "";
32
33 String dest = "C:\\快盘\\English\\NewConcept_2_UK";
34 String destFile = "";
35 InputStream inputStream = null;
36 OutputStream outputStream = null;
37 CloseableHttpClient httpClient = null;
38 CloseableHttpResponse response = null;
39
40 byte[] buffer = new byte[4096];
41
42 for (int i = start; i < end; i ++) {
43
44 //
45 fileName = pattern.replaceAll("\\{x\\}", StringUtils.leftPad(i + "", bitNum, "0"));
46 urlStr = prefix + fileName;
47 HttpGet get = new HttpGet(urlStr);
48
49 destFile = dest + "\\" + fileName;
50 try {
51
52 System.out.println(urlStr);
53 httpClient = HttpClients.createDefault();
54 response = httpClient.execute(get);
55 inputStream = response.getEntity().getContent();
56 outputStream = new FileOutputStream(destFile);
57
58 int bytesRead = -1;
59 while ((bytesRead = inputStream.read(buffer)) != -1) {
60 outputStream.write(buffer, 0, bytesRead);
61 }
62
63 System.out.println("downloaded!" + destFile);
64 System.out.println();
65 System.out.println(" --- ");
66 System.out.println();
67 } catch (IOException e) {
68 e.printStackTrace();
69 } finally {
70
71 if (inputStream != null) {
72 try {
73 inputStream.close();
74 } catch (IOException e) {
75 e.printStackTrace();
76 }
77 }
78
79 if (outputStream != null) {
80 try {
81 outputStream.close();
82 } catch (IOException e) {
83 e.printStackTrace();
84 }
85 }
86
87 if (response != null) {
88 try {
89 response.close();
90 } catch (IOException e) {
91 e.printStackTrace();
92 }
93 }
94
95 if (httpClient != null) {
96 try {
97 httpClient.close();
98 } catch (IOException e) {
99 e.printStackTrace();
100 }
101 }
102 }
103
104 }
105 }
106 }
107