Java 获取网页内容 - 使用 URL 和 URLConnection
使用 Java 语言获取网页的网络内容,可以使用 Java 的 URL 和 URLConnection 类。
首先,导入 Java 的 URL 和 URLConnection 类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
然后,使用 URL 类创建一个 URL 对象,传入要获取内容的网址:
URL url = new URL('https://example.com');
接下来,使用 URL 对象的 openConnection 方法创建一个 URLConnection 对象:
URLConnection connection = url.openConnection();
然后,可以设置一些连接属性,如请求头信息:
connection.setRequestProperty('User-Agent', 'Mozilla/5.0');
接下来,使用 URLConnection 对象的 getInputStream 方法获取输入流,并用 BufferedReader 读取内容:
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
最后,可以将获取到的内容进行处理或输出:
System.out.println(content.toString());
完整的示例代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL('https://example.com');
URLConnection connection = url.openConnection();
connection.setRequestProperty('User-Agent', 'Mozilla/5.0');
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
System.out.println(content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:在实际使用中可能需要处理异常和添加其他属性或参数,具体根据需要进行调整。
原文地址: http://www.cveoy.top/t/topic/pghP 著作权归作者所有。请勿转载和采集!