import java.net.*;
import java.io.*;

public class urlconnection
{
    public static void main(String[] args)
    {
        StringBuffer document = new StringBuffer();
        try 
        {
            URL url = new URL("http://www.163.com");
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null)
            document.append(line + " ");
            reader.close();
        }
        catch (MalformedURLException e) 
        {
            e.printStackTrace(); 
        }
        catch (IOException e)
        {
            e.printStackTrace(); 
        }
        System.out.println(document.toString());
    }
}
==========================================================
方法二:
==========================================================
import java.net.*;
import java.io.*;

public class useSourceViewer
{
    public static void main (String[] args) 
    {
        if (args.length > 0) 
        {
            try 
            {

                URL u = new URL(args[0]);
                InputStream in = u.openStream( );

                in = new BufferedInputStream(in);

                Reader r = new InputStreamReader(in);
                int c;
                while ((c = r.read( )) != -1) 
                {
                    System.out.print((char) c);
                }
                Object o = u.getContent( );
                System.out.println("I got a " + o.getClass().getName( ));
            }
            catch (MalformedURLException e) 
            {
                System.err.println(args[0] + " is not a parseable URL");
            }
            catch (IOException e) 
            {
                System.err.println(e);
            }
        } 
    }
}

posted on 2008-07-13 20:38 aisoft 阅读(10367) 评论(5)  编辑  收藏 所属分类: J2EE开发技术

FeedBack:
# re: Java 读取网页Html文件[未登录]
2008-07-14 20:17 | javaread.com
如果要获取网页文本内容,还可以配合htmlparser  回复  更多评论
  
# re: Java 读取网页Html文件
2008-08-18 19:36 | qq630202528
怎么读取源文件中【 和 】之间的内容?  回复  更多评论
  
# re: Java 读取网页Html文件[未登录]
2009-04-13 21:29 | GreatGhoul
还是第一种方法好用.  回复  更多评论
  
# re: Java 读取网页Html文件
2010-12-30 16:07 | 路人
这个方法是会出错的,((line = reader.readLine()) != null 是可能出错,有可能网页没有读取完成就遇见这样的空行 本人亲自测试遇见过  回复  更多评论
  
# re: Java 读取网页Html文件
2011-12-10 15:27 | XU
比较喜欢第一种方法  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
<2011年12月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

随笔档案(2)

文章分类(12)

文章档案(12)

收藏夹

搜索

  •  

最新评论