• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java爬虫系列一HttpClient请求工具,IP代理模式

武飞扬头像
大鹏-coder
帮助1

IP代理模式顾名思义,使用非本机IP来请求目标数据,两大好处:

  • 1.作为爬虫项目,有效防止IP风控
  • 2.不多说,你懂得~

特此声明:本人所有文章都只供大家学习,任何个人或组织不得直接或间接使用本文所有文章中的技术内容干违背国家法律规定的业务。如因此造成的一切后果本人概不承担。

另附《中华人民共和国网络安全法》大家以此为底线,一定要保持职业操守,做合法社会主义好公民


废话不多,直接上源码。

1.Maven依赖

  1.  
    <dependency>
  2.  
    <groupId>org.apache.httpcomponents</groupId>
  3.  
    <artifactId>httpclient</artifactId>
  4.  
    <version>4.5.3</version>
  5.  
    </dependency>

2.为了支持Https协议,所以我们还需要写个绕过SSL验证的工具

  1.  
    //添加主机名验证程序类,设置不验证主机
  2.  
    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
  3.  
    public boolean verify(String hostname, SSLSession session) {
  4.  
    return true;
  5.  
    }
  6.  
    };
  7.  
     
  8.  
    /**
  9.  
    * 创建SSL安全连接
  10.  
    *
  11.  
    * @return
  12.  
    */
  13.  
    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
  14.  
    SSLConnectionSocketFactory sslsf = null;
  15.  
    try {
  16.  
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
  17.  
    new TrustStrategy() {
  18.  
    public boolean isTrusted(X509Certificate[] chain, String authType) {
  19.  
    return true;
  20.  
    }
  21.  
    }).build();
  22.  
    sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
  23.  
     
  24.  
    @Override
  25.  
    public boolean verify(String arg0, SSLSession arg1) {
  26.  
    return true;
  27.  
    }
  28.  
    });
  29.  
    } catch (GeneralSecurityException e) {
  30.  
    e.printStackTrace();
  31.  
    }
  32.  
    return sslsf;
  33.  
    }
学新通

3.为了解决很多莫名其妙的的异常,我们有必要详细点来捕获各种可能的异常,并选择抛出或者返回,方便后续处理。

  • ConnectTimeoutException,SocketTimeoutException异常:连接超时
  • 其它的都不重要,可以统一Exception捕获

4.Get方式请求

全局设置超时时间,大家根据自己实际情况设置

private final static int CONNECTION_TIME_OUT = 6000;
  1.  
    /**
  2.  
    * Get方式请求
  3.  
    * @param pageUrl 请求地址
  4.  
    * @param charset 编码方式
  5.  
    * @param params 参数
  6.  
    * @param proxyIp 代理IP
  7.  
    * @return
  8.  
    */
  9.  
    public static Map<String, Object> doGet(String pageUrl, String charset, Map<String, String> params, String proxyIp) {
  10.  
    Map<String, Object> map = new HashMap<String, Object>();
  11.  
    String result = null;
  12.  
    if (null == charset) {
  13.  
    charset = "utf-8";
  14.  
    }
  15.  
    //设置绕过SSL请求验证
  16.  
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).build();
  17.  
    try {
  18.  
    URL url = new URL(pageUrl);
  19.  
    //设置代理协议
  20.  
    HttpHost target = new HttpHost(url.getHost(), url.getDefaultPort(), url.getProtocol());
  21.  
    HttpHost proxy = new HttpHost(proxyIp.split(":")[0], Integer.parseInt(proxyIp.split(":")[1]));
  22.  
    RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(CONNECTION_TIME_OUT)
  23.  
    .setConnectionRequestTimeout(CONNECTION_TIME_OUT).setSocketTimeout(CONNECTION_TIME_OUT).build();
  24.  
    HttpGet httpget = new HttpGet(url.toString());
  25.  
    httpget.setConfig(config);
  26.  
    try {
  27.  
    for (Map.Entry<String, String> entry : params.entrySet()) {
  28.  
    httpget.addHeader(entry.getKey(), entry.getValue());
  29.  
    }
  30.  
    } catch (Exception e) {
  31.  
    }
  32.  
    CloseableHttpResponse response = null;
  33.  
    try {
  34.  
    response = httpclient.execute(target, httpget);
  35.  
    if (response != null) {
  36.  
    HttpEntity resEntity = response.getEntity();
  37.  
    if (resEntity != null) {
  38.  
    result = EntityUtils.toString(resEntity, charset);
  39.  
    map.put("res", result);
  40.  
    }
  41.  
    Header[] headerinfo = response.getAllHeaders();
  42.  
    map.put("headerinfo", headerinfo);
  43.  
    }
  44.  
    } catch (Exception e) {
  45.  
    map.put("res", "error");
  46.  
    log.info("Connection refused: connect:{}", e.getMessage());
  47.  
    } finally {
  48.  
    try {
  49.  
    response.close();
  50.  
    } catch (NullPointerException e) {
  51.  
    map.put("res", "error");
  52.  
    log.info("无响应结果");
  53.  
    }
  54.  
    }
  55.  
    }catch (ConnectTimeoutException | SocketTimeoutException e) {
  56.  
    log.info("请求超时");
  57.  
    map.put("res", "error");
  58.  
    return map;
  59.  
    }catch (ClientProtocolException e) {
  60.  
    e.printStackTrace();
  61.  
    } catch (IOException e) {
  62.  
    e.printStackTrace();
  63.  
    } finally {
  64.  
    try {
  65.  
    httpclient.close();
  66.  
    } catch (IOException e) {
  67.  
    e.printStackTrace();
  68.  
    }
  69.  
    }
  70.  
    return map;
  71.  
    }
学新通

5.Post方式请求一,模拟Form表单方式提交参数,即构造Map传递参数(自定义请求头信息)

  1.  
    /**
  2.  
    * Post方式请求
  3.  
    * @param pageUrl 请求地址
  4.  
    * @param params 请求参数
  5.  
    * @param charset 编码方式
  6.  
    * @param header 请求头
  7.  
    * @param proxyIp 代理IP
  8.  
    * @return
  9.  
    */
  10.  
    public static Map<String, Object> doPost(String pageUrl, String params, String charset, Map<String, String> header, String proxyIp) {
  11.  
    // log.info("===========================================【POST请求信息】==================================================");
  12.  
    // log.info("|| 【POST地址】-{}",pageUrl);
  13.  
    // log.info("|| 【请求参数】{}",params);
  14.  
    // log.info("===========================================================================================================");
  15.  
    Map<String, Object> resMap = new HashMap<String, Object>();
  16.  
    String result = null;
  17.  
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).build();
  18.  
    try {
  19.  
    URL url = new URL(pageUrl);
  20.  
    HttpHost target = new HttpHost(url.getHost(), url.getDefaultPort(), url.getProtocol());
  21.  
    HttpHost proxy = new HttpHost(proxyIp.split(":")[0], Integer.parseInt(proxyIp.split(":")[1]));
  22.  
    RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(CONNECTION_TIME_OUT)
  23.  
    .setConnectionRequestTimeout(CONNECTION_TIME_OUT).setSocketTimeout(CONNECTION_TIME_OUT).build();
  24.  
    HttpPost httpPost = new HttpPost(url.toString());
  25.  
    httpPost.setConfig(config);
  26.  
    try {
  27.  
    if (null != header) {
  28.  
    Set<Map.Entry<String, String>> entries = header.entrySet();
  29.  
    for (Map.Entry<String, String> entry : entries) {
  30.  
    httpPost.addHeader(entry.getKey(), entry.getValue());
  31.  
    }
  32.  
    }
  33.  
    } catch (Exception e) {
  34.  
    }
  35.  
    // httpPost.setEntity(new StringEntity(params));
  36.  
    // httpPost.setEntity(new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED));
  37.  
    StringEntity stringEntity = new StringEntity(params);
  38.  
    stringEntity.setContentType("application/x-www-form-urlencoded");
  39.  
    httpPost.setEntity(stringEntity);
  40.  
    CloseableHttpResponse response = null;
  41.  
    try {
  42.  
    response = httpclient.execute(target, httpPost);
  43.  
    if (response != null) {
  44.  
    HttpEntity resEntity = response.getEntity();
  45.  
    if (resEntity != null) {
  46.  
    result = EntityUtils.toString(resEntity, "UTF-8");
  47.  
    // log.info("===============================================【返回结果】==================================================");
  48.  
    // log.info("|| {}",result);
  49.  
    // log.info("===========================================================================================================");
  50.  
    resMap.put("res", result);
  51.  
    }
  52.  
    Header[] headerinfo = response.getAllHeaders();
  53.  
    resMap.put("headerinfo", headerinfo);
  54.  
    // log.info("===============================================【返回头部】==================================================");
  55.  
    // log.info("===========================================================================================================");
  56.  
    }
  57.  
    } catch (Exception e) {
  58.  
    resMap.put("res", "error");
  59.  
    log.info("Connection refused: connect:{}", e.getMessage());
  60.  
    } finally {
  61.  
    try {
  62.  
    response.close();
  63.  
    } catch (NullPointerException e) {
  64.  
    resMap.put("res", "error");
  65.  
    log.info("无响应结果");
  66.  
    }
  67.  
    }
  68.  
    }catch (ConnectTimeoutException | SocketTimeoutException e) {
  69.  
    // log.info("====请求超时=====");
  70.  
    log.info("【POST请求异常1】---->",e.getMessage());
  71.  
    resMap.put("res", "error");
  72.  
    return resMap;
  73.  
    }catch (ClientProtocolException e) {
  74.  
    // e.printStackTrace();
  75.  
    log.info("【POST请求异常2】---->",e.getMessage());
  76.  
    resMap.put("res", "error");
  77.  
    return resMap;
  78.  
    } catch (IOException e) {
  79.  
    log.info("【POST请求异常3】---->",e.getMessage());
  80.  
    // e.printStackTrace();
  81.  
    resMap.put("res", "error");
  82.  
    return resMap;
  83.  
    }finally {
  84.  
    try {
  85.  
    httpclient.close();
  86.  
    } catch (IOException e) {
  87.  
    e.printStackTrace();
  88.  
    }
  89.  
    }
  90.  
    return resMap;
  91.  
    }
学新通

6.Post方式请求二,模拟JSON数据方式提交参数,即以字符串方式传递参数(自定义请求头信息)

  1.  
    /**
  2.  
    * 只针对提交JSON字符串方式
  3.  
    * @param pageUrl
  4.  
    * @param params
  5.  
    * @param charset
  6.  
    * @param header
  7.  
    * @param proxyIp
  8.  
    * @return
  9.  
    */
  10.  
    public static Map<String, Object> doPostByJson(String pageUrl, String params, String charset, Map<String, String> header, String proxyIp) {
  11.  
    log.info("===========================================【doPostByJson-POST请求信息】==================================================");
  12.  
    log.info("|| 【POST地址】-{}",pageUrl);
  13.  
    log.info("|| 【请求参数】{}",params);
  14.  
    log.info("===========================================================================================================");
  15.  
    Map<String, Object> resMap = new HashMap<String, Object>();
  16.  
    String result = null;
  17.  
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).build();
  18.  
    try {
  19.  
    URL url = new URL(pageUrl);
  20.  
    HttpHost target = new HttpHost(url.getHost(), url.getDefaultPort(), url.getProtocol());
  21.  
    HttpHost proxy = new HttpHost(proxyIp.split(":")[0], Integer.parseInt(proxyIp.split(":")[1]));
  22.  
    RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(CONNECTION_TIME_OUT)
  23.  
    .setConnectionRequestTimeout(CONNECTION_TIME_OUT).setSocketTimeout(CONNECTION_TIME_OUT).build();
  24.  
    HttpPost httpPost = new HttpPost(url.toString());
  25.  
    httpPost.setConfig(config);
  26.  
    try {
  27.  
    if (null != header) {
  28.  
    Set<Map.Entry<String, String>> entries = header.entrySet();
  29.  
    for (Map.Entry<String, String> entry : entries) {
  30.  
    httpPost.addHeader(entry.getKey(), entry.getValue());
  31.  
    }
  32.  
    }
  33.  
    } catch (Exception e) {
  34.  
    e.printStackTrace();
  35.  
    }
  36.  
    //参数
  37.  
    List<BasicNameValuePair> pair =new ArrayList<BasicNameValuePair>();
  38.  
    pair.add(new BasicNameValuePair("data", params));
  39.  
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pair,"UTF-8");
  40.  
    httpPost.setEntity(entity);
  41.  
     
  42.  
    Header[] allheader = httpPost.getAllHeaders();
  43.  
    for (int i = 0; i < allheader.length; i ) {
  44.  
    log.info("||--请求头信息-->{}",allheader[i]);
  45.  
    }
  46.  
     
  47.  
    CloseableHttpResponse response = httpclient.execute(target, httpPost);
  48.  
    log.info("||--请求参数-->{}",EntityUtils.toString(httpPost.getEntity(),"UTF-8"));
  49.  
    try {
  50.  
    if (response != null) {
  51.  
    HttpEntity resEntity = response.getEntity();
  52.  
    if (resEntity != null) {
  53.  
    result = EntityUtils.toString(resEntity, "UTF-8");
  54.  
    log.info("===============================================【返回结果】==================================================");
  55.  
    log.info("|| {}",result);
  56.  
    log.info("===========================================================================================================");
  57.  
    resMap.put("res", result);
  58.  
    }
  59.  
    Header[] headerinfo = response.getAllHeaders();
  60.  
    resMap.put("headerinfo", headerinfo);
  61.  
    log.info("===============================================【返回头部】==================================================");
  62.  
    log.info("===========================================================================================================");
  63.  
    }
  64.  
    } finally {
  65.  
    response.close();
  66.  
    }
  67.  
    }catch (ConnectTimeoutException | SocketTimeoutException e) {
  68.  
    // log.info("====请求超时=====");
  69.  
    log.info("【POST请求异常1】---->",e.getMessage());
  70.  
    resMap.put("res", "error");
  71.  
    return resMap;
  72.  
    }catch (ClientProtocolException e) {
  73.  
    // e.printStackTrace();
  74.  
    log.info("【POST请求异常2】---->",e.getMessage());
  75.  
    resMap.put("res", "error");
  76.  
    return resMap;
  77.  
    } catch (IOException e) {
  78.  
    log.info("【POST请求异常3】---->",e.getMessage());
  79.  
    // e.printStackTrace();
  80.  
    resMap.put("res", "error");
  81.  
    return resMap;
  82.  
    }finally {
  83.  
    try {
  84.  
    httpclient.close();
  85.  
    } catch (IOException e) {
  86.  
    e.printStackTrace();
  87.  
    }
  88.  
    }
  89.  
    return resMap;
  90.  
    }
学新通

7.响应的实体类工具

  1.  
    /**
  2.  
    * 获得响应HTTP实体内容
  3.  
    *
  4.  
    * @param response
  5.  
    * @return
  6.  
    * @throws IOException
  7.  
    * @throws UnsupportedEncodingException
  8.  
    */
  9.  
    private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
  10.  
    HttpEntity entity = response.getEntity();
  11.  
    if (entity != null) {
  12.  
    InputStream is = entity.getContent();
  13.  
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  14.  
    String line = br.readLine();
  15.  
    StringBuilder sb = new StringBuilder();
  16.  
    while (line != null) {
  17.  
    sb.append(line "\n");
  18.  
    line = br.readLine();
  19.  
    }
  20.  
    return sb.toString();
  21.  
    }
  22.  
    return "";
  23.  
    }
学新通

到此,基本整个工具类就完事了。具体用法我们下一篇再写吧。

拜拜了您嘞~

这篇好文章是转载于:编程之路

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 编程之路
  • 本文地址: /boutique/detail/tanhhacbci
系列文章
更多 icon
同类精品
更多 icon
继续加载