编写一个阅览网页的代码
时间: 2024-04-21 07:26:32 浏览: 23
在 Java 中,你可以使用 HttpURLConnection 或者 HttpClient 来实现阅览网页的代码。以下是使用 HttpURLConnection 的示例代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ReadWebPage {
public static void main(String[] args) throws IOException {
// 创建一个 URL 对象
URL url = new URL("https://www.example.com");
// 打开一个 HttpURLConnection 连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
connection.setRequestMethod("GET");
// 设置请求头部
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 获取响应代码和响应消息
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response Code: " + responseCode);
System.out.println("Response Message: " + responseMessage);
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
reader.close();
// 打印响应内容
System.out.println(stringBuilder.toString());
}
}
```
这段代码会打开一个 HttpURLConnection 连接,发送一个 GET 请求到 https://www.example.com,并且读取响应内容。你可以根据需要修改请求的 URL 和请求头部,来实现阅览你想要访问的网页。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)