用Java编写一个程序用于获取网络中的某个资源(https://www.baidu.com),并将内容显示在命令行窗口中。
时间: 2024-02-09 16:06:58 浏览: 24
好的,您可以使用Java中的HttpURLConnection类和BufferedReader类来实现这个问题。以下是示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String url = "https://www.baidu.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println(response.toString());
} else {
System.out.println("Failed to get the resource.");
}
}
}
```
这个程序会向指定的URL发起一个GET请求,并获取响应的内容,最后将内容打印在命令行窗口中。如果请求成功,状态码为200,就会打印出响应的内容;否则,会提示请求失败。