forked from gaopu/Java
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDownloadImg.java
More file actions
Latest commit
82 lines (73 loc) · 2.81 KB
/
Copy pathDownloadImg.java
File metadata and controls
82 lines (73 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
importorg.apache.http.HttpEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.util.EntityUtils;
importjava.io.*;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
publicclassDownloadImg {
publicstaticvoidwriteImgEntityToFile(HttpEntityimgEntity,StringfileAddress) {
FilestoreFile = newFile(fileAddress);
FileOutputStreamoutput = null;
try {
output = newFileOutputStream(storeFile);
if (imgEntity != null) {
InputStreaminstream;
instream = imgEntity.getContent();
byteb[] = newbyte[8 * 1024];
intcount;
while ((count = instream.read(b)) != -1) {
output.write(b, 0, count);
}
}
} catch (FileNotFoundExceptione) {
e.printStackTrace();
} catch (IOExceptione) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOExceptione) {
e.printStackTrace();
}
}
}
publicstaticvoidmain(String[] args) {
System.out.println("获取Bing图片地址中……");
SimpleDateFormatdateFormat = newSimpleDateFormat("yyyy-MM-dd");
CloseableHttpClienthttpClient = HttpClients.createDefault();
HttpGethttpGet = newHttpGet("http://cn.bing.com/");
CloseableHttpResponseresponse = null;
try {
response = httpClient.execute(httpGet);
Patternp = Pattern.compile("g_img=\\{url:.*\\.jpg");
Matcherm = p.matcher(EntityUtils.toString(response.getEntity()));
Stringaddress = null;
if (m.find()) {
address = m.group().split("'")[1].split("'")[0];
} else {
System.exit(0);
}
System.out.println("图片地址:" + address);
System.out.println("正在下载……");
HttpGetgetImage = newHttpGet(address);
CloseableHttpResponseresponseImg = httpClient.execute(getImage);
HttpEntityentity = responseImg.getEntity();
writeImgEntityToFile(entity,"/home/geekgao/图片/BingImg/" + dateFormat.format(newDate()) + ".jpg");
System.out.println("下载完毕.");
} catch (IOExceptione) {
e.printStackTrace();
} finally {
try {
httpClient.close();
response.close();
} catch (IOExceptione) {
e.printStackTrace();
}
}
}
}