详解Java实现多种方式的http数据抓取

 更新时间:2016年12月27日 11:38:48   作者:Sea_Sky  
本篇文章主要介绍了Java实现多种方式的http数据抓取,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧。

前言:

时下互联网第一波的浪潮已消逝,随着而来的基于万千数据的物联网时代,因而数据成为企业的重要战略资源之一。基于数据抓取技术,本文介绍了java相关抓取工具,并附上demo源码供感兴趣的朋友测试!

1)JDK自带HTTP连接,获取页面或Json

 

2) JDK自带URL连接,获取页面或Json

 

3)HttpClient Get工具,获取页面或Json

 

 4)commons-io工具,获取页面或Json

 

5) Jsoup工具(通常用于html字段解析),获取页面,非Json返回格式】

 

--------------------------------------------------------------------------------

完整代码:

package com.yeezhao.common.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;

/**
 * http工具对比
 * 
 * @author Administrator -> junhong
 *
 *     2016年12月27日
 */
public class HttpFetchUtil {
  
  /**
   * 获取访问的状态码
   * @param request
   * @return
   * @throws Exception
   */
  public static int getResponseCode(String request) throws Exception {
    URL url = new URL(request);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    return conn.getResponseCode();

  }
  /**
   * 1)JDK自带HTTP连接,获取页面或Json
   * @param request
   * @param charset
   * @return
   * @throws Exception
   */
  public static String JDKFetch(String request, String charset) throws Exception {
    URL url = new URL(request);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //模拟浏览器参数
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36"
        + " (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
      InputStream input = conn.getInputStream();
      StringBuffer sb = new StringBuffer();
      BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset));
      String s;
      while ((s = reader.readLine()) != null) {
        sb.append(s + "\n");
      }
      input.close();
      conn.disconnect();
      return sb.toString();
    }
    return "";
  }
  /**
   * 2) JDK自带URL连接,获取页面或Json
   * @param request
   * @param charset
   * @return
   * @throws Exception
   */
  public static String URLFetch(String request, String charset) throws Exception {
    URL url = new URL(request);
    return IOUtils.toString(url.openStream());
  }

  /**
   * 3)HttpClient Get工具,获取页面或Json
   * @param url
   * @param charset
   * @return
   * @throws Exception
   */
  public static String httpClientFetch(String url, String charset) throws Exception {
    // GET
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setContentCharset(charset);
    HttpMethod method = new GetMethod(url);
    httpClient.executeMethod(method);
    return method.getResponseBodyAsString();
  }
  /**
   * 4)commons-io工具,获取页面或Json
   * @param url
   * @param charset
   * @return
   * @throws Exception
   */
  public static String commonsIOFetch(String url, String charset) throws Exception {
    return IOUtils.toString(new URL(url), charset);
  }
  
  /**
   * 5) Jsoup工具(通常用于html字段解析),获取页面,非Json返回格式
   * @param url
   * @return
   * @throws Exception
   */
  public static String jsoupFetch(String url) throws Exception {
    return Jsoup.parse(new URL(url), 2 * 1000).html();
  }

}

测试代码:

package com.yeezhao.common.http;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
 * 测试类
 * 3个测试链接:
 * 1)百科网页
 * 2)浏览器模拟获取接口数据
 * 3)获取普通接口数据
 * @author Administrator -> junhong
 *
 * 2016年12月27日
 */
public class HttpFetchUtilTest {
  String seeds[] = {"http://baike.baidu.com/view/1.htm","http://m.ximalaya.com/tracks/26096131.json","http://remyapi.yeezhao.com/api/query?wd=%E5%91%A8%E6%98%9F%E9%A9%B0%E7%9A%84%E7%94%B5%E5%BD%B1"};
  final static String DEFAULT_CHARSET = "UTF-8";
  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
    System.out.println("--- down ---");
  }

  @Test
  public void testGetResponseCode() throws Exception{
    for(String seed:seeds){
      int responseCode = HttpFetchUtil.getResponseCode(seed);
      System.out.println("ret="+responseCode);
    }
  }

  @Test
  public void testJDKFetch() throws Exception{
    for(String seed:seeds){
      String ret = HttpFetchUtil.JDKFetch(seed, DEFAULT_CHARSET);
      System.out.println("ret="+ret);
    }
  }

  @Test
  public void testURLFetch() throws Exception{
    for(String seed:seeds){
      String ret = HttpFetchUtil.URLFetch(seed, DEFAULT_CHARSET);
      System.out.println("ret="+ret);
    }
  }

  @Test
  public void testHttpClientFetch()throws Exception {
    for(String seed:seeds){
      String ret = HttpFetchUtil.httpClientFetch(seed, DEFAULT_CHARSET);
      System.out.println("ret="+ret);
    }
  }

  @Test
  public void testCommonsIOFetch()throws Exception {
    for(String seed:seeds){
      String ret = HttpFetchUtil.commonsIOFetch(seed, DEFAULT_CHARSET);
      System.out.println("ret="+ret);
    }
  }

  @Test
  public void testJsoupFetch() throws Exception{
    for(String seed:seeds){
      String ret = HttpFetchUtil.jsoupFetch(seed);
      System.out.println("ret="+ret);
    }
  }

}

附:相关jar依赖

...
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.7.3</version>
</dependency>

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
...

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java8使用Supplier启动ScheduledThread代码实例

    Java8使用Supplier启动ScheduledThread代码实例

    这篇文章主要介绍了Java8使用Supplier启动ScheduledThread详解,项目开启立即启动定时任务是很多项目都会遇到的一个需求,如何利用Java提供的函数优雅的写出来十分考验一个人的功底,需要的朋友可以参考下
    2024-01-01
  • 浅谈js文件引用方式及其同步执行与异步执行

    浅谈js文件引用方式及其同步执行与异步执行

    下面小编就为大家带来一篇浅谈js文件引用方式及其同步执行与异步执行。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • MyBatis动态SQL之<choose><when><otherwise>标签的使用

    MyBatis动态SQL之<choose><when><otherwise>标签的使用

    MyBatis中动态语句choose-when-otherwise 类似于Java中的switch-case-default语句,本文就来介绍一下MyBatis动态SQL之<choose><when><otherwise>标签的使用,感兴趣的可以了解一下
    2023-09-09
  • java实现向有序数组中插入一个元素实例

    java实现向有序数组中插入一个元素实例

    本篇文章主要介绍了java实现向有序数组中插入一个元素实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • java学习之JasperReport踩坑

    java学习之JasperReport踩坑

    本篇文章介绍的是在JAVA学习中JasperReport遇到的坑以及解决办法,有需要的朋友参考下吧。
    2018-01-01
  • 代码实例Java IO判断目录和文件是否存在

    代码实例Java IO判断目录和文件是否存在

    本篇文章给大家分享了Java IO判断目录和文件是否存在的代码,对此有需要的读者们可以跟着小编一起学习下。
    2018-02-02
  • java获取当前日期和时间的二种方法分享

    java获取当前日期和时间的二种方法分享

    这篇文章主要介绍了java获取当前日期和时间的二种方法,需要的朋友可以参考下
    2014-03-03
  • 在 Spring Boot 中集成 MinIO 对象存储

    在 Spring Boot 中集成 MinIO 对象存储

    MinIO 是一个开源的对象存储服务器,专注于高性能、分布式和兼容S3 API的存储解决方案,本文将介绍如何在 Spring Boot 应用程序中集成 MinIO,以便您可以轻松地将对象存储集成到您的应用中,需要的朋友可以参考下
    2023-09-09
  • Java 3年面试经验告诉你Mybatis是如何进行分页的

    Java 3年面试经验告诉你Mybatis是如何进行分页的

    这篇文章主要介绍了Java 3年面试经验告诉你Mybatis是如何进行分页的,对于任何ORM框架,分页的实现逻辑无外乎两种,不管怎么包装,最终给到开发者的,只是使用上的差异而已,本文给大家讲解的很明白,感兴趣的朋友一起看看吧
    2022-09-09
  • IDEA安装详细步骤(多图预警)

    IDEA安装详细步骤(多图预警)

    这篇文章主要介绍了IDEA安装详细步骤(多图预警),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04

最新评论