分享

Java教程分享使用HttpClient抓取页面内容

 好程序员IT 2019-11-23

Java教程分享使用HttpClient抓取页面内容,使用HttpClient工具来发送Http请求

1.简介

HttpClient Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus HTMLUnit 都使用了 HttpClient

HttpClient 相比传统 JDK 自带的 URLConnection,增加了易用性和灵活性,它不仅是客户端发送 HTTP 请求变得容易,而且也方便了开发人员测试接口(基于 HTTP 协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握 HttpClient 是很重要的必修内容,掌握 HttpClient 后,相信对于 HTTP 协议的了解会更加深入。

2.应用场景

3.HttpClient工具的使用

1)添加依赖

<!-- Apache Http Begin -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>fluent-hc</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.5</version>
</dependency>
<!-- Apache Http End -->

2)编写测试代码

  @Test
    public void testHttpClient() throws IOException {

        //1.获得HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //2.创建请求对象,如果是post请求  HttpPost  如果是get请求  HttpGet对象
        String uri = "http://www.baidu.com";
        HttpGet get = new HttpGet(uri);
        //3.执行get请求,获得响应消息对象
        CloseableHttpResponse response = client.execute(get);
        //4.获取响应行
        StatusLine statusLine = response.getStatusLine();
        //5.获取状态码
        int code = statusLine.getStatusCode();
        if(code==200){
            //响应成功
            HttpEntity entity = response.getEntity();
            //6.获取响应体中的内容
//            InputStream is = entity.getContent();
//            byte[] b = new byte[8192];
//            int len = 0;
//            while((len = is.read(b))!=-1){
//                System.out.println(new String(b,0,len));
//            }
//            is.close();
            System.out.println(EntityUtils.toString(entity, "utf-8"));
        }


    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多