HttpComponents

一 概述

1.HttpComponents的作用

HttpComponents的作用是模拟浏览器获取网页内容。

二 使用

1.使用HttpComponents需要先导入架包。

2.使用

        CloseableHttpClient client = HttpClients.createDefault();// 创建一个客户端对象
        HttpGet httpGet = new HttpGet("http://www.ifeng.com/");// 请求对象
        // 设置具体信息,使请求模拟浏览器
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:53.0) Gecko/20100101 Firefox/53.0");
        // 使用代理IP,因为长时间从一个网站抓取内容,IP可能被禁掉,因此采用高匿代理,使网站无法发现访问者使用的是代理与IP
        HttpHost proxy = new HttpHost("116.226.90.12", 808);
        // 自定义请求,比如连接超时、响应超时、代理
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000)
                .setProxy(proxy).build();
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = client.execute(httpGet);// 客户端执行请求,获得响应对象
        HttpEntity entity = response.getEntity();// 获取响应体
        String responseBody = EntityUtils.toString(entity);// 将响应体对象转化为字符串
        InputStream is = entity.getContent();
        File destination = new File("Files", "content.txt");
        FileUtils.copyToFile(is, destination);
发布了1 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u011927449/article/details/105609796