现在的位置: 首页 > 综合 > 正文

通过URL对象获取指定网页的内容

2013年08月03日 ⁄ 综合 ⁄ 共 2029字 ⁄ 字号 评论关闭
Code:
  1. import java.net.URL;    
  2. import java.net.URLConnection;    
  3. import java.io.*;    
  4. import java.util.Date;   
  5. import java.util.Scanner;   
  6.   
  7. public class Test {   
  8.     public static void main(String[] args) {   
  9.         ReadHtml rh = new ReadHtml();   
  10.         rh.getWebPage();   
  11.         rh.displayAll();   
  12.     }   
  13. }   
  14.   
  15. class ReadHtml {   
  16.     private URL u;   
  17.     private URLConnection uc;                 
  18.     String addr = new String();             //用来存放网址   
  19.     Scanner sc = new Scanner(System.in);    //用来输入网址   
  20.     File f = new File("webpage.html");      //创建一个存放网页的文件   
  21.     InputStreamReader in;                   //创建一个文件输入流   
  22.     OutputStreamWriter out;                 //创建一个文件输出流   
  23.     char[] buf = new char[1024];            //每次读写1k内容   
  24.     public ReadHtml() {   
  25.         try {   
  26.             System.out.println("请输入文件的URL地址:");   
  27.             addr = sc.nextLine();                  
  28.             u = new URL(addr);                  //定义URL对象   
  29.             uc = u.openConnection();            //获得一个URLConnection对象   
  30.             uc.connect();                       //连接   
  31.             in = new InputStreamReader(uc.getInputStream());   
  32.             out = new OutputStreamWriter(new FileOutputStream(f));   
  33.         } catch(IOException e) {   
  34.             e.printStackTrace();   
  35.         }   
  36.     }   
  37.     public void getWebPage() {   
  38.         try {   
  39.             while(in.read(buf, 0, buf.length) > 0) {   
  40.                 out.write(buf, 0, buf.length);   
  41.             }   
  42.             in.close();   
  43.             out.close();     //关闭流   
  44.         } catch(IOException e) {   
  45.             e.printStackTrace();   
  46.         }   
  47.     }   
  48.     //打印所有信息   
  49.     public void displayAll() {   
  50.         System.out.println("内容类型: "+uc.getContentType());    
  51.         System.out.println("内容编码: "+uc.getContentEncoding());    
  52.         System.out.println("内容长度: "+uc.getContentLength());    
  53.         System.out.println("创建日期: "+new Date(uc.getDate()));    
  54.         System.out.println("最后修改日期: "+new Date(uc.getLastModified()));    
  55.         System.out.println("终止日期: "+new Date(uc.getExpiration()));    
  56.     }   
  57. }  

studying

抱歉!评论已关闭.