HttpConnectionUtil.java
2.64 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
83
84
85
86
87
88
89
90
91
92
package com.topdraw.sohu.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpConnectionUtil {
private static final Logger log = LoggerFactory
.getLogger(HttpConnectionUtil.class);
/**
* @param strUrlPath 下载路径
* @param strDownloadDir 下载存放目录
* @param strDownloadDir 下载文件重命名(null保持原有名字)
* @return 返回下载文件
*/
public static File downloadFile(String strUrlPath, String strDownloadDir, String strFileName) {
File file = null;
try {
// 统一资源
URL url = new URL(strUrlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Accept-Encoding", "identity");
httpURLConnection.setReadTimeout(10000);
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 文件名
String filePathUrl = strFileName == null ? httpURLConnection.getURL().getFile() : strFileName;
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
//log.info("file length -> " + fileLength);
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
String path = strDownloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 打印下载百分比
// log.info("下载了 -> " + len * 100 / fileLength);
}
bin.close();
out.close();
if (file.length() != fileLength && fileLength != -1) {
log.info("file size mismatch: " + fileLength + " -> " + file.length());
file = null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
file = null;
} catch (IOException e) {
e.printStackTrace();
file = null;
}
return file;
}
public static void main(String[] args) {
}
}