获取站点源代码

获取站点内容有多种方式我这里介绍两种,一种是通过HTTPSocket对象获取,另一种是通过HttpURLConnection对象获取

1、采用HTTPSocket对象要应用一个叫做heaton的抓取页面的包可以去网上找到下载

参考代码如下:

  1. import com.heaton.bot.*;
  2. class HTTPGet {
  3.     public static void main(String args[]) {
  4.         String url;
  5.         try {
  6.             if (args.length != 1) {
  7.             }
  8.             // 要获取的页面
  9.             url = "http://club.china.alibaba.com/forum/thread/view/96_24986738_.html";
  10.             HTTPSocket http = new HTTPSocket();
  11.             http.send(url, null);// 向url发送请求
  12.             System.out.println("* * Headers from: " + url + "* *");
  13.             for (int i = 0; i < http.getClientHeaders().length(); i++) {
  14.                 Attribute a = http.getServerHeaders().get(i);// 获取头信息
  15.                 System.out.println(a.getName() + "=" + a.getValue());
  16.             }
  17.             System.out.println("* * * Data from: " + url + "* * *");
  18.             System.out.println(http.getBody());// 获取源代码
  19.             System.exit(0);
  20.         } catch (Exception e) {
  21.             System.out.println("Exception thrown: " + e.getMessage());
  22.         }
  23.     }
  24. }

 

2、通过HttpURLConnection对象获取页面,通过HttpURLConnection对象获取页面的头信息和编码信息,通过URL对象获取页面的源代码。参考代码:

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.HttpURLConnection;
  5. import java.net.MalformedURLException;
  6. import java.net.URL;
  7. public class WebSpider {
  8.     /**
  9.      * @param args
  10.      */
  11.     public static void main(String[] args) {
  12.         try{
  13.             URL aurl=new URL("http://www.csdn.net");
  14.             HttpURLConnection urlcon=(HttpURLConnection) aurl.openConnection();
  15.             //初始化HttpURLConnection对象
  16.             System.out.println(urlcon.getHeaderField(0));//获取页面头信息
  17.             System.out.println(urlcon.getContentType());
  18.             //采用UTF-8读取页面源文件,这里采用的字符集必须与页面相匹配,不匹配可能会出现乱码
  19.             BufferedReader bin=new BufferedReader(new InputStreamReader(aurl.openStream(),"utf-8"));
  20.             String line = "";
  21.             while((line=bin.readLine())!=null){
  22.                 System.out.print(line);
  23.                 System.out.print('/n');
  24.             }
  25.             
  26.         }catch(MalformedURLException e){
  27.             System.out.println("URL error/n");
  28.         }catch(IOException e2){
  29.             System.out.println("IO error/n");
  30.         }
  31.     }
  32. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值