
The URL class of the java.net package represents a Uniform Resource Locator which is used to point a resource (file or, directory or a reference) in the world wide web.
The openStream() method of this class opens a connection to the URL represented by the current object and returns an InputStream object using which you can read data from the URL.
Therefore, to read data from web page (using the URL class) −
Instantiate the java.net.URL class by passing the URL of the desired web page as a parameter to its constructor.
AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。它不是新的编程语言,而是一种使用现有标准的新方法,最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容,不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。《php中级教程之ajax技术》带你快速
2114
立即学习“Java免费学习笔记(深入)”;
Invoke the openStream() method and retrieve the InputStream object.
Instantiate the Scanner class by passing the above retrieved InputStream object as a parameter.
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadingWebPage {
public static void main(String args[]) throws IOException {
//Instantiating the URL class
URL url = new URL("http://www.something.com/");
//Retrieving the contents of the specified page
Scanner sc = new Scanner(url.openStream());
//Instantiating the StringBuffer class to hold the result
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(sc.next());
//System.out.println(sc.next());
}
//Retrieving the String from the String Buffer object
String result = sb.toString();
System.out.println(result);
//Removing the HTML tags
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!
以上就是Java中如何在不使用任何外部库的情况下读取网页内容?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号