-
Notifications
You must be signed in to change notification settings - Fork 0
/
AwfulDownloader.java
87 lines (80 loc) · 2.41 KB
/
AwfulDownloader.java
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
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.StringTokenizer;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
class AwfulDownloader
{
public AwfulDownloader(String urlText)
{
try
{
URL url = new URL(urlText);
URLConnection coNe;
switch(url.getProtocol())
{
case "http":
{
HttpURLConnection coNeHTTP = (HttpURLConnection) url.openConnection();
coNeHTTP.setRequestMethod("GET");
coNeHTTP.setRequestProperty("User-Agent", userAgent);
//System.out.println("Response Code: " + coNeHTTP.getResponseCode());
coNe = coNeHTTP;
break;
}
case "https":
{
HttpsURLConnection coNeHTTPS = (HttpsURLConnection) url.openConnection();
coNeHTTPS.setRequestMethod("GET");
coNeHTTPS.setRequestProperty("User-Agent", userAgent);
//System.out.println("Response Code: " + coNeHTTPS.getResponseCode());
coNe = coNeHTTPS;
break;
}
default:
{
System.out.println("Unsupported Protocol!");
return;
}
}
fileName = getFilename(url.getPath());
OutputStream outputStream = new FileOutputStream(fileName == null ? "output.txt" : fileName);
long startTime = System.currentTimeMillis();
InputStream inputStream = coNe.getInputStream();
byte[] buffer = new byte[inputStream.available()];
int bytesNum;
while((bytesNum = inputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, bytesNum);
}
outputStream.close();
System.out.println("Download Complete.\nTime Cost: " + (System.currentTimeMillis() - startTime) + "ms");
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
//String defaultURL = "https://mirrors.neusoft.edu.cn/eclipse/oomph/epp/2020-09/R/eclipse-inst-jre-win64.exe";
String defaultURL = "https://osananajimi.moe/content/images/size/w2000/2020/07/DSC01321.jpg";
//String defaultURL = "https://api64.ipify.org/";
AwfulDownloader pdl = new AwfulDownloader(args.length == 0 ? defaultURL : args[0]);
}
private String getFilename(String path)
{
StringTokenizer token = new StringTokenizer(path, "/");
while(token.hasMoreTokens())
{
fileName = token.nextToken();
}
return fileName;
}
private String userAgent = "Awful Downloader v0.1";
private String fileName;
}