抓取网页信息

今天学习了网页抓取,,现在只想把自己所学的,所用的,同大家分享!

AliexCategory.java   

// 需要的jar 有: commons-httpcllient3.1.jar    commons-logging.jar commons-codec.jar

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;

public  class AliexCategory{

private static final String categoryUrl=http://www.iteye.com;

private static final String CHARSET= "utf8";

public  static String getHtml(String url){ 

HttpClient hc = new HttpClient();

 

HttpMethod  get = null;

 if(StringUtils.isEmpty(url))

return "" ;

String page = "";

 

 try {
   //  设置cookie的兼容性,这一行必须要加,否则服务器无法获取登陆状态
   hc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); 
  get = new GetMethod(url);
   get.getParams().setContentCharset(CHARSET);

   int statusCode =  hc.executeMethod(get);

if(statusCode==HttpStatus.SC_OK){

      page= get.getResponseBodyAsString()

  }

 // System.out.println("http头中的编码信息charset : "+ get.getResponseCharSet());  

  
  } catch (Exception e) {
   logger.error("getHtml exception,url:"+url, e);
   e.printStackTrace();
   page = "";
  } finally {
   if (get != null) {
    get.releaseConnection();  //  无论执行是否成功,都必须释放连接
   }
  }
            return page;

}

 

 

  // 在main方法中直接调用getHtml 测试即可

public static void main(String[] args) {

  String html = getHtml(categoryUrl);

System.out.println(html);

  }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值