-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebClient.java
83 lines (64 loc) · 2.58 KB
/
WebClient.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
/*
* Name:-Dhruvi Shah
* 10015504023
* Project - 1
* -----------------------------------------------------
* The program is a client server application that allows the user to download a file from the server.
*
* Steps to run the client on command line:-
* 1. Open command prompt.
* 2. Open the directiory where the project is stored.
* 3. Compile the code using "javac WebClient.java"
* 4. Execute the following command "java WebClient localhost 6789 Test.html".
* 5. The program will then connect to the server and download the file if it exists and store the file in the downloads folder.
*
* Reference:
* - Programming Assignment - 1 (Document provided on Blackboard)
* - http://www.codejava.net/java-se/networking/use-httpurlconnection-to-download-file-from-an-http-url
*
*/
import java.io.*;
import java.net.* ;
import java.util.GregorianCalendar;
public class WebClient {
public static Socket server;
public static void main(String args[]) throws Exception {
// Store the required server information from the command line.
String host = args[0];
int portNo = Integer.parseInt(args[1]);
String Filename = args[2];
//Establish a connection
String fileURL = "http://" + host + ":" + portNo + "/" + Filename;
//Open a connection
URL url = new URL(fileURL);
long finish = 0;
long start = new GregorianCalendar().getTimeInMillis();
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
//Get the response code
int responseCode = httpconn.getResponseCode();
System.out.println("ResponseCode: " + responseCode);
//If the response code is "OK", download the file
if(responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("File Exists");
//Status and content message
System.out.println("Status: " + httpconn.getResponseMessage());
System.out.println("Content-Type: " + httpconn.getContentType());
InputStream input = httpconn.getInputStream();
FileOutputStream output = new FileOutputStream("C:/Users/Admin/Downloads/" + Filename);
//Download the file
int bytesRead = -1;
byte[] buffer = new byte[1024];
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
finish = new GregorianCalendar().getTimeInMillis();
System.out.println("RTT: " + (finish - start + "ms"));
System.out.println("File Copied");
//Close all the streams
input.close();
output.close();
} else {
System.out.println("File does not exist");
}
}
}