Java基于httpclient获取网页数据,实现简单网络爬虫

1、pom文件引入httpclient依赖

    <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>    

2、直接上代码

public static void getInternetData(String url) {
        logger.info("目标网络地址:url="+url);
        //初始化httpclient
        CloseableHttpClient client = HttpClients.createDefault();
        //get方法请求
        HttpGet getMethod = new HttpGet(url);
        //post方法请求
        HttpPost postMethod = new HttpPost(url);
        try {
            //执行响应 ,初始化response    
            CloseableHttpResponse response = client.execute(getMethod);
            //获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();            
            logger.info("访问响应状态码,statusCode="+statusCode);
            //获取实体内容
            String entity = EntityUtils.toString(response.getEntity(),"utf-8");
            logger.info("访问网络响应信息:response="+entity);
            //消耗实体:关闭HttpEntity的流实体
            EntityUtils.consume(response.getEntity());
            response.close();
            client.close();
        } catch (Exception e) {
            logger.info("获取网络数据异常",e);
        }
    }  

    public static void main(String[] args) {
        getInternetData("https://cn.bing.com/");
    }

猜你喜欢

转载自blog.csdn.net/weixin_42315600/article/details/84146944