zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    算法系列:杂项
    算法系列:
    Algo: Dynamic programming
    Algo:
    算法系列:XXX
    算法系列:量子计算与量子通信
    算法系列:Reservoir Sampling
    算法系列:CSAPP 推荐
    算法系列:
    算法系列:geometry
  • 原文地址:https://www.cnblogs.com/tonghun/p/6951854.html
Copyright © 2011-2022 走看看