public class UrlHtml { public static void main(String[] args) throws Exception {
//通过地址获取URL对象 URL url = new URL("https://manhua.dmzj.com");
//解析URL
System.out.println(
"URL 是 "
+ url.toString());
System.out.println(
"协议是 "
+ url.getProtocol());
System.out.println(
"文件名是 "
+ url.getFile());
System.out.println(
"主机是 "
+ url.getHost());
System.out.println(
"路径是 "
+ url.getPath());
System.out.println(
"端口号是 "
+ url.getPort());
System.out.println(
"默认端口号是 "
+ url.getDefaultPort());
//获取URL文件流 BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter (new FileWriter("data.html")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } reader.close(); writer.close();
//连接URL
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
long date = httpCon.getDate();
Map<String, List<String>> headerFields = httpCon.getHeaderFields();
Set<String> keys = headerFields.keySet();
/获取URL响应头信息
for( String key : keys ){
String val = httpCon.getHeaderField(key);
System.out.println(key+" "+val);
}
System.out.println( httpCon.getLastModified() );
if (date == 0)
System.out.println("无法获取信息。");
else
System.out.println("Date: " + new Date(date));
} }