HttpURLConnection使用

HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。 

和Httpclient 一样都可以用来抓取网页,不过HttpClient更强大。

 

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

/** *//**
 * 网页阅读器.
 * 

 */
public class PageReader {
    
//连接对象
    private static HttpURLConnection conn;

    
/** *//**
     * 根据url连接某地址,并返回返回码.
     * 返回码说明:
     *         0~200为正常情况,其中200为OK
     *         其余都为错误的情况,具体请参见w3
     * 
@param urlStr 需连接的url字符串
     
*/

    private int connect(String urlStr) throws Exception {
        URL url 
= new URL(urlStr);
        conn 
= (HttpURLConnection) url.openConnection();
        System.out.println(
"返回码: " + conn.getResponseCode());
        
//如果定向的地址经过重定向,
        
//那么conn.getURL().toString()显示的是重定向后的地址
        System.out.println(conn.getURL().toString());
        
return conn.getResponseCode();
    }

 

/** *//**
     * 读取网页的内容.
     * 
@return 返回网页的内容
     
*/

    
private String readContents() throws Exception {
        BufferedReader in 
= null;
        StringBuffer sb 
= new StringBuffer();
        in 
= new BufferedReader(new InputStreamReader(conn
                .getInputStream()));

        String inputLine;
        
while ((inputLine = in.readLine()) != null{
            sb.append(inputLine);
            sb.append(
"\n");
        }

        
return sb.toString();
    }

 

/** *//**
     * 中断连接.
     
*/

    
private void disconnect() {
        conn.disconnect();
    }

    

    /** *//**
     * 测试方法
     * 
@param args
     * 
@throws Exception
     
*/

    
public static void main(String[] args) throws Exception {
        PageReader reader 
= new PageReader();
        String url 
= "http://hexapixel.com/download.php?                                                      file=com.hexapixel.widgets.ribbon.alphatest.src.jar";
        reader.connect(url);
        String content 
= reader.readContents();
        System.out.println(
"网页内容:" + content);
        reader.disconnect();
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值