package step2; import java.io.InputStream; import java.net.URL; import java.util.Scanner; public class URLContent { public static void main(String[] args) throws Exception{ // ---------------------Begin------------------------ String str_url = "http://www.baidu.com"; // ---------------------End------------------------ } }
时间: 2025-06-20 17:57:27 浏览: 7
### 使用Java从URL读取内容的示例代码
在Java中,可以通过使用`java.net.URL`和`java.net.HttpURLConnection`类来从指定的URL读取内容。以下是一个完整的代码示例,展示了如何实现这一功能[^2]。
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLContentReader {
public static void main(String[] args) {
String urlStr = "https://example.com"; // 替换为实际的URL地址
try {
// 创建URL对象
URL url = new URL(urlStr);
// 打开连接并获取HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000); // 设置连接超时时间为5秒
connection.setReadTimeout(5000); // 设置读取超时时间为5秒
// 检查响应码是否成功
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 使用BufferedReader读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine).append("\n");
}
in.close();
// 输出读取到的内容
System.out.println("URL内容:\n" + content.toString());
} else {
System.out.println("无法读取URL内容,HTTP响应码: " + responseCode);
}
connection.disconnect(); // 关闭连接
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码实现了从指定URL读取内容的功能,并将其输出到控制台。以下是代码的关键点:
- 使用`java.net.URL`类创建一个表示目标URL的对象。
- 调用`openConnection()`方法打开与URL的连接,并将返回的`URLConnection`对象转换为`HttpURLConnection`以支持HTTP协议。
- 设置请求方法为`GET`,并配置连接和读取的超时时间[^2]。
- 检查HTTP响应码是否为`200 OK`,如果是,则通过`BufferedReader`逐行读取响应内容并存储到`StringBuilder`中[^2]。
- 最后关闭连接并处理可能发生的异常。
#### 注意事项
- 确保目标URL是可访问的,并且服务器支持HTTP GET请求。
- 如果需要处理HTTPS连接,可能还需要配置SSL上下文或信任管理器[^2]。
阅读全文
相关推荐

















