Java获取网页内容

以前都是用python写爬虫,这次使用java。代码虽然多了点,不过还是静态类型语言代码提示舒心点。获取网页源代码算是爬虫的基本入门吧。

我们采用Apache的commons-httpclient包进行抓取。需要用到三个包:commons-httpclient、commons-codec、commons-logging。用maven则只需添加如下dependency即可:

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

核心代码如下:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.IOException;

public class Main {

    public static String readUrl(String url) {
        PostMethod method = new PostMethod(url);
        String res = null;
        try {
            new HttpClient().executeMethod(method);
            res = new String(method.getResponseBodyAsString().getBytes(), "utf8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(readUrl("http://blog.zzkun.com"));
    }
}

爬取本博客网站,执行结果如下:

posted @ 2016-05-05 19:12  Popco  阅读(116)  评论(0编辑  收藏  举报