java.net包的URL类表示一个统一资源定位符,用于在万维网上指向资源(文件,目录或引用)。
此类提供了各种构造函数,其中一个接受String参数并构造URL类的对象。
的OpenStream()此类的方法打开到URL的连接表示由当前对象,并返回使用它可以读取来自URL数据的InputStream对象。
因此,要从网页读取数据(使用URL类)-
通过将所需网页的URL作为参数传递给其构造函数来实例化java.net.URL类。
调用该openStream()
方法并检索InputStream对象。
通过传递上面获取的InputStream对象作为参数来实例化Scanner类。
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadingWebPage {
public static void main(String args[]) throws IOException {
//实例化URL类
URL url = new URL("http://www.something.com/");
//检索指定页面的内容
Scanner sc = new Scanner(url.openStream());
//实例化StringBuffer类以保存结果
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(sc.next());
//System.out.println(sc.next());
}
//从字符串缓冲区对象中检索字符串
String result = sb.toString();
System.out.println(result);
//删除HTML标签
result = result.replaceAll("<[^>]*>", "");
System.out.println("Contents of the web page: "+result);
}
}
输出结果
<html><body><h1>Itworks!</h1></body></html>
Contents of the web page: Itworks!