Java快速开发平台

www.fastunit.com

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  23 Posts :: 0 Stories :: 273 Comments :: 0 Trackbacks

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLUtil {

  
public static String getHtml(String urlString) {
    
try {
      StringBuffer html 
= new StringBuffer();
      URL url 
= new URL(urlString);
      HttpURLConnection conn 
= (HttpURLConnection) url.openConnection();
      InputStreamReader isr 
= new InputStreamReader(conn.getInputStream());
      BufferedReader br 
= new BufferedReader(isr);
      String temp;
      
while ((temp = br.readLine()) != null) {
        html.append(temp).append(
"\n");
      }
      br.close();
      isr.close();
      
return html.toString();
    } 
catch (Exception e) {
      e.printStackTrace();
      
return null;
    }
  }

  
public static void main(String[] args) {
    System.out.println(URLUtil.getHtml(
"http://www.fastunit.com"));
  }
}
posted on 2008-03-26 12:22 FastUnit 阅读(8702) 评论(7)  编辑  收藏 所属分类: Java

Feedback

# 顶死你 2008-03-26 16:23 草包书生
还是不错,用sorckt类实现起来效果更好。
不过用URL也不错嘛。  回复  更多评论
  

# re: 通过url地址抓取网页html代码 2008-03-26 17:52 隔叶黄莺
用 HttpURLConnection 比直接用 Socket 肯定要简单多了,Socket 的话要按照 Http 协议来发送请求。  回复  更多评论
  

# re: 通过url地址抓取网页html代码 2008-03-27 10:06 hejianhuacn
使用wget的java实现会更好  回复  更多评论
  

# re: 通过url地址抓取网页html代码 2008-03-27 21:52 leson
URL src = new URL( "http://www.yahoo.com" );
File dest = new File( "times.html" );
FileUtils.copyURLToFile( src, dest );

Apache Commons里面封装成这样了。  回复  更多评论
  

# re: 通过url地址抓取网页html代码 2008-03-28 14:06 勉勉强强
@leson

确实是Apache Commons的包装用得最简便,呵呵  回复  更多评论
  

# re: 通过url地址抓取网页html代码[未登录] 2012-03-07 18:19 zt
不知道楼主有没有遇到过抓取到的html不完整的情况。我用类似上面的代码抓网页时有时会遇到得到的html不完整  回复  更多评论
  

# re: 通过url地址抓取网页html代码[未登录] 2012-09-09 02:01 L
IOUtils.toString(URL u,Charsets encoding)  回复  更多评论
  


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


网站导航: