81,092
社区成员
发帖
与我相关
我的任务
分享
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
class GetPageSource {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: GetPageSource URL");
return;
}
String strURL = args[0];
URL url = null;
try {
url = new URL(strURL);
} catch (MalformedURLException e) {
System.err.println("Invalid format of URL:" + url + "," + e.getMessage());
return;
}
URLConnection urlCon = null;
try {
urlCon = url.openConnection();
} catch (IOException e) {
System.err.println("Can't get connection from URL: " + e.getMessage());
}
// print properties of this url
System.out.println("Date: " + new Date(urlCon.getDate()));
System.out.println("Content-Type: " + urlCon.getContentType());
System.out.println("Expires: " + urlCon.getExpiration());
System.out.println("Last-Modified: " + new Date(urlCon.getLastModified()));
System.out.println("Content-Length: " + urlCon.getContentLength());
// download page source from this url
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = urlCon.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
int count = 0;
String tmp = null;
while ( (tmp = reader.readLine()) != null ) {
System.out.println(tmp);
count += tmp.length();
}
System.out.println("Count = " + count);
} catch (IOException e) {
System.err.println("I/O failed: " + e.getMessage());
} finally {
try {
if (reader != null) reader.close();
} catch (IOException e) { }
}
}
}