Android-爬取网页内容的几种方法

本文介绍了在Android中使用urlConnection进行网页内容抓取的方法,通过HttpURLConnection对象结合InputStreamReader,将网页内容转化为字符串进行处理。


记录几种抓取网页数据的办法,就是已知一个网页的域名,获取网页内容为一个String字符串或者Document对象。

第一种:urlConnection,通过url类的openConnection()方法,得到一个HttpURLConnection对象。通过InputStreamReader将整个网页内容转为String字符串。

URL url = new URL(Url);
        HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
        if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
        {       
            Log.d("TAG", "---into-----urlConnection---success--");
             
            InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");
            int i;
            String content = "";
            while((i = isr.read()) != -1)
            {
                content = content + (char)i;
            }
            
            isr.close();
            httpConn.disconnect();
        }else
        {
            Log.d("TAG", "---into-----urlConnection---fail--");
             
        }
第二种:httpClient ,将url放入一个httpget对象中,然后用httpClient的excute方法去得到httpResponse的对象或者直接得到网页的String串。

   DefaultHttpClient httpClinet = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(Url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
        	
            String content = httpClinet.execute(httpGet, responseHandler);
            //HttpResponse resp = httpClinet.execute(httpGet);
        } catch (ClientProtocolException e) {
             
            e.printStackTrace();
        } catch (IOException e) {
             
            e.printStackTrace();
        }
第三种:使用Jsoup:Document doc = Jsoup.parse(new URL("http://www.baidu.com"), 5000);






评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值