返回顶部

收藏

java使用URL和URLConnection类下载Url内容

更多

这个例子演示如何使用URL和URLConnection类下载网页内容。

首先需要创建一个URL对象,然后通过url.openConnection()方法得到URLConnection类实例。

然后调用URLConnection的getInputStream()方法获得响应流,然后读入到StringBuffer中。

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Main.java
 *
 * @author outofmemory.cn
 */
public class Main {

    /**
     * Reads a web page into a StringBuilder object
     * and prints it out to console along with the
     * size of the page.
     */
    public void getWebSite() {

        try {

            URL url = new URL("http://www.google.com");
            URLConnection urlc = url.openConnection();

            BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());

            StringBuilder builder = new StringBuilder();
            int byteRead;
            while ((byteRead = buffer.read()) != -1)
                builder.append((char) byteRead);

            buffer.close();

            System.out.println(builder.toString());
            System.out.println("The size of the web page is " + builder.length() + " bytes.");

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().getWebSite();
    }
}

标签:java,HTTP,URLConnection

收藏

0人收藏

支持

0

反对

0

发表评论